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

时间:2013-05-21 07:36:32

标签: java spring spring-mvc

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

我现在遇到一种情况,我希望从非bean类访问服务bean,特别是RequestContextAwareTag实现。

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

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

如果bean在调度程序上下文中注册,我会得到NoSuchBeanDefinitionException

如果可能的话,我实际上更愿意在根上下文中注册我的@Service bean而不选择@Controller bean,然后在@Controller bean中选择<context:component-scan/>个bean。调度员背景。 ApplicationContext的问题在于它同时存在。

如果无法做到这一点,我需要一种方法来访问调度程序{{1}}以检索服务bean。

非常感谢任何指导。

1 个答案:

答案 0 :(得分:2)

我已设法通过使用component-scanexclude-filter分割两个include-filter配置来解决此问题。

根上下文:

<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>
相关问题