2013-05-21 44 views
1

我有一個spring-mvc應用程序,它在DispatcherServlet上下文配置中使用了<context:component-scan base-package="com.example.app" />自動佈線的bean。如何從servlet上下文而不是根上下文獲取bean?

我現在有一種情況,我希望從非bean類訪問服務bean,特別是RequestContextAwareTag實現。

如下我可以訪問根上下文註冊的bean:

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

如果bean是在調度方面註冊的,我得到一個NoSuchBeanDefinitionException

如果有可能我會更喜歡我的@Service豆根方面沒有@Controller豆被拾起來註冊,然後有@Controller豆在調度方面回升。 <context:component-scan/>的問題是兩者兼而有之。

如果這是不可能的,我需要一種方法來訪問調度員ApplicationContext來檢索服務bean。

任何指導將非常感激。

+0

您是否嘗試過實施了ApplicationContextAware和實例化類在bean的配置文件? – shazin

+0

不幸的是,這是不可能的標籤,因爲它們是在每個使用標籤的頁面請求上創建的。 –

回答

2

我已經設法通過使用exclude-filterinclude-filter拆分兩個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> 
+0

root-context意味着bean在web-xml中用標籤「context-param」聲明瞭一個? – verystrongjoe

相關問題