In a spring mvc project, I want to inject a @Controller into a different bean, something like this:
@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, just as e.g. @Service (which does work):
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com..Mycontroller] is defined
I've also tried to get the bean from the ApplicationContext directly.
I'd like to avoid any discussions about why I want to inject controllers and that I should rather create an additional level of abstraction and inject it instead :)
I'm going to assume that your SomeSpringBean
class is component scanned by the root context loaded by the ContextLoaderListener
.
I'm going to assume that your @Controller
annotated classes are scanned by the servlet context loaded by the DispatcherServlet
.
In this case, the root context does not have access to the beans in the servlet context. Only the inverse is true.
You will need to put the SomeSpringBean
class in some other package that will have to be scanned by the servlet context.
If my assumptions are wrong, please add your context configurations.
This is not a good idea. @Controller
beans are meant to be managed by the DispatcherServlet
's HandlerMapping
stack. I can't think of anything you would want to get from a @Controller
bean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With