Inject @Controller in another spring bean

In the spring mvc project, I want to insert @Controller into another bean, something like this:

@Controller public class MyController { .. } @Component public class SomeSpringBean { @Resource private MyController myController; .. } 

This does not work, although the @Controller annotation is a specialization of @Component, such as @Service (which works):

 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com..Mycontroller] is defined 

I also tried to get a bean from ApplicationContext directly.

I would like to avoid any discussion about why I want to introduce controllers, and that I should rather create an extra layer of abstraction and introduce it instead :)

+7
java spring spring-mvc dependency-injection
source share
1 answer

I assume that your SomeSpringBean class is a component scanned by the root context loaded by the ContextLoaderListener .

I am going to assume that your annotated @Controller classes @Controller checked by the servlet context loaded by the DispatcherServlet .

In this case, the root context does not have access to beans in the servlet context. Only the opposite is true.

You will need to put the SomeSpringBean class in another package that needs to be checked by the servlet context.


If my assumptions are wrong, add a context configuration.


This is not a good idea. @Controller beans are for managing the DispatcherServlet HandlerMapping stack. I canโ€™t think of anything you would like to get from the @Controller bean.

+5
source share

All Articles