Wojciech Górski
Wojciech Górski

Reputation: 943

Inject @Controller into another spring bean

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 :)

Upvotes: 8

Views: 6104

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

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.

Upvotes: 6

Related Questions