Java – inject @ controller into another spring bean
In a spring MVC project, I want to inject a @ controller into a different bean, as shown below:
@Controller public class MyController { .. } @Component public class SomeSpringBean { @Resource private MyController myController; .. }
This doesn't seem to work, although the @ controller annotation is a specialization of @ component, such as @ service (indeed valid):
org.springframework.beans.factory.NoSuchBeanDeFinitionException: No qualifying bean of type [com..Mycontroller] is defined
I also try to get beans directly from ApplicationContext
I want to avoid discussing why I want to inject the controller. I'd rather create an additional level of abstraction and inject it:)
Solution
I'll assume that your somespringbean class is a component of the root context scan loaded by the contextloaderlistener
I'll assume that your @ controller annotation class is scanned by the servlet context loaded by the dispatcher servlet
In this case, the root context does not have access to beans in the servlet context Only the reverse is true
You need to place the somespringbean class in some other package that must be scanned by the servlet context
If my assumption is wrong, please add your context configuration
This is not a good idea@ The controller bean means that it is managed by the handlermapping stack of the dispatcher servlet I can't think of anything you want from @ controller bean