Announcement Announcement Module
Collapse
No announcement yet.
Dao configuration for JPA and spring: Could not autowire field Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dao configuration for JPA and spring: Could not autowire field

    Hello,
    I'm trying to configure a DAO structure in my application so I created a generic Dao interface:
    Code:
    public interface Dao<E, K> {
        public void persist(E entity);
        public void remove(E entity);
        public E findById(K id);
    }
    I implemented the Specific Dao for an entity:
    Code:
    public interface DaoRole extends Dao<Role, Integer>{
    //some other specific DAO method for Role entity
    }
    Then I created a specific Dao implementation for JPA:
    Code:
    public abstract class JpaDao <E, K> implements Dao<E, K> {
    	protected Class<E> entityClass;
    
    	@PersistenceContext
    	protected EntityManager entityManager;
     
    	public JpaDao() {
    		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    		this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
    	}
     
    	@Transactional
    	public void persist(E entity) { entityManager.persist(entity); }
    	public void remove(E entity) { entityManager.remove(entity); }
    	public E findById(K id) { return entityManager.find(entityClass, id); }
    }
    And a the end my specific implementation for JPA DAO for Role entity:
    Code:
    @Repository
    public class JpaDaoRole extends JpaDao<Role, Integer> implements DaoRole {
     	//implementation of the methos in DaoRole
    }
    So I created a Junit test to test the application that contains an autowired field:
    Code:
    @Autowired
    public JpaDaoRole dr;
    But when I launch the application I get an error:
    Code:
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.windy.spring.JpaDaoRole] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    The strange thing is that if I implement all the methods in the JPADaoRole class everything works perfectly and the field can be autowired. I think the problem is caused by the Dao structure I'm using... any help on how to solve this problem?

    Thanks in advance for your help.
    Danilo

  • #2
    I just found the solution.

    I should have autowired the generic implementation:

    @Autowired
    public DaoRole dr;

    Comment

    Working...
    X