Java – Why @Autowired not work out side a controller class spring mvc

autowiredexceptionjavaspring-mvc

I have a Spring MVC project. I have a class controller , service and dao layer.

@Controller
public class HomeController {

    @Autowired
    private PersonFacade personFacade;
   ....
}

I have my service class

@Service
@Transactional
public class PersonFacadeImpl implements PersonFacade{

    @Autowired
    private PersonDAO personDAOdef;

    //code ....
}

And finally my DAO class

@Repository
public class PersonDAOImpl implements PersonDAO{
    @Autowired
    private SessionFactory sessionFactory;
     //code
}

This works PERFECTLY, my problem its here:

I did a class listener and I would like use the PersonFacade with @Autowired

public class PersonListener extends AbstractRepositoryEventListener<Person> {

    @Autowired
    private PersonFacade personFacade;
    .... //code 
}

And I have this exception :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name      
'personListener': Injection of autowired dependencies failed; nested exception is      
org.springframework.beans.factory.BeanCreationException: Could not autowire field:   
private com.gabrielglez.main.Facade.PersonFacade 
com.gabrielglez.main.evenlistener.PersonListener.personFacade; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of 
type [com.gabrielglez.main.Facade.PersonFacade] 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)}

I have this class in other package and I don't know why in this class Spring can't create the object and inside the controller works perfectly.

I don't know what is happening.

Here its my servlet-context : https://github.com/tsw1985/HelloHibernate/blob/master/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml

In a few words, if I want to inject one dependency with @Autowired out side a controller class , I will have the same problem. Thanks to all.

Please if you help my you will save my life because I have one week with this problem.

Thanks to all !!

Best Answer

@Autowired works only in objects which are managed by Spring. So annotate your class PersonListener for example with @Component and don't create instance as new Object(). Use for example @Autowired to get instance.