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

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

    I'm trying to configure a DAO structure in my application so I created a generic Dao interface:
    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:
    public interface DaoRole extends Dao<Role, Integer>{
    //some other specific DAO method for Role entity
    Then I created a specific Dao implementation for JPA:
    public abstract class JpaDao <E, K> implements Dao<E, K> {
    	protected Class<E> entityClass;
    	protected EntityManager entityManager;
    	public JpaDao() {
    		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    		this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
    	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:
    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:
    public JpaDaoRole dr;
    But when I launch the application I get an error:
    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.

  • #2
    I just found the solution.

    I should have autowired the generic implementation:

    public DaoRole dr;