繁体   English   中英

如何从servlet上下文而不是根上下文中获取bean?

[英]How can I get a bean from the servlet context instead of the root context?

我有一个spring-mvc应用程序,该应用程序通过在DispatcherServlet上下文配置中使用<context:component-scan base-package="com.example.app" />自动装配了bean。

现在,我希望从非bean类(特别是RequestContextAwareTag实现)访问服务bean。

我可以按以下方式访问在根上下文中注册的bean:

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(
      pageContext.getSession().getServletContext());
MyService svc = ctx.getBean(MyService.class);

如果Bean在分派器上下文中注册, NoSuchBeanDefinitionException收到NoSuchBeanDefinitionException

如果可能的话,我实际上希望在不使用@Controller Bean的情况下在根上下文中注册@Service Bean,然后在调度程序上下文中使用@Controller Bean。 <context:component-scan/>在于它兼有两者。

如果不可能,那么我需要一种方法来访问调度ApplicationContext来检索服务bean。

任何指导将不胜感激。

我设法通过使用exclude-filterinclude-filter拆分两个component-scan配置来解决此问题。

根上下文:

<context:component-scan  base-package="com.example.app">
  <context:exclude-filter
    expression="org.springframework.stereotype.Controller"
    type="annotation"/>
</context:component-scan>

的servlet上下文:

<mvc:annotation-driven/>
<context:component-scan  base-package="com.example.app">
  <context:include-filter
    expression="org.springframework.stereotype.Controller"
    type="annotation"/>
</context:component-scan>

暂无
暂无

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

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