简体   繁体   English

将@Controller注入另一个spring bean

[英]Inject @Controller into another spring bean

In a spring mvc project, I want to inject a @Controller into a different bean, something like this: 在一个spring mvc项目中,我想将一个@Controller注入一个不同的bean,如下所示:

@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 eg @Service (which does work): 这似乎不起作用,虽然@Controller注释是@Component的特化,就像@Service(它确实有效)一样:

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. 我也尝试直接从ApplicationContext获取bean。

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 . 我将假设您的SomeSpringBean类是由ContextLoaderListener加载的根上下文扫描的组件。

I'm going to assume that your @Controller annotated classes are scanned by the servlet context loaded by the DispatcherServlet . 我将假设您的@Controller注释类由DispatcherServlet加载的servlet上下文进行扫描。

In this case, the root context does not have access to the beans in the servlet context. 在这种情况下,根上下文无权访问servlet上下文中的bean。 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. 您需要将SomeSpringBean类放在一些必须由servlet上下文扫描的其他包中。


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. @Controller bean意味着由DispatcherServletHandlerMapping堆栈管理。 I can't think of anything you would want to get from a @Controller bean. 我想不出你想从@Controller bean得到什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM