Search code examples
springspring-annotations

Could not autowire field on extending DAO and Manager interface


Hi my application was working fine, but on extending my Manager and Dao interface I am getting the error. I have tried the solution (changing <context:component-scan base-package="com.controller" /> to <context:component-scan base-package="com" />) posted in various posts but that gives me stackOverflowError . I think some annotations is required while extending the interfaces, but i do not know what annotation should be used there. Please guide me

//Controller

@Controller
public class Controller {

    @Autowired
    private Manager2<Entity> manager;

//Manager Interfaces and Impl

public interface Manager1 <T> {
    public void add(T entity);
    public List<T> getAll();
    public T getById(Integer id);
    public void delete(Integer id);
    public void update(T entity);
}

public interface Manager2<T> extends  Manager1<T>  {
    public List<Entity> getList(int Id);
}

@Service
public class ManagerImpl implements Manager2<Entity>  {
    @Autowired
    private Manager2<Entity> dao;
}

//Dao Interfaces and Impl

public interface DAO1 <T> {
    public void add(T entity);
    public List<T> getAll();
    public T getById(Integer id);
    public void delete(Integer id);
    public void update(T entity);
}

public interface DAO2<T> extends  DAO1<T>  {
    public List<Entity> getList(int Id);
}

public class DaoImpl implements DAO2<Entity>  {
    @Autowired
    private SessionFactory sessionFactory;
}

//declaration in servlet.xml

<context:component-scan base-package="com.controller" />
<bean id="dao" class="com.dao.DaoImpl"></bean>
<bean id="manager" class="com.service.ManagerImpl"></bean>

//Error from log file

nested exception is `org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.service.Manager2] 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)}`

Solution

  • the issue with stackoverflow happens because of this code

    @Service
    public class ManagerImpl implements Manager2<Entity>  {
        @Autowired
        private Manager2<Entity> dao;
    }
    

    the reason for this behaviour is that it there's a recursive dependency which is never resolved. service needs another service with same bean recipe. additionally, @autowired annotation is used for resolving dependency byType. that means that having 2 instantiated beans with save type would lead to an error, as spring is not able to understand what bean you really need. in this case you could use either @Resource (byName) or add @Qualifier annotation with name of a bean you need.