2013-07-05 61 views
0

訪問一個Spring bean我有一個Spring bean在我的applicationContext定義如下:從Servlet

<bean id="spaceReader" class="com.company.SpaceReader"> 
</bean> 

我希望能在我的應用程序Servlet來訪問這個bean,而無需使用:

ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXT_LOCATION); 
context.getBean("SpaceReader"); 

我嘗試使用下面的出口是:

<bean id="ContextExporter" class="org.springframework.web.context.support.ServletContextAttributeExporter"> 
    <property name="contextExporterAttributes"> 
     <map> 
      <entry key="SpaceReaderKey"> 
      <ref local="spaceReader" /> 
     </entry> 
     </map> 
    </property> 
</bean> 

但是當我把它注射我在Servlet中,它返回一個空值。只是想知道當我導出Bean時或者當我嘗試在Servlet中訪問它時是否缺少某些東西?

+1

添加展示你是如何試圖檢索您的servlet上下文中的bean的代碼。 – Keith

+0

spaceReader =(SpaceReader)getServletContext()。getAttribute(「SpaceReader」); – user676567

+0

是否有可能你的代碼應該使用小寫本地引用?空間讀取器=(SpaceReader)getServletContext()。getAttribute(「spaceReader」); - –

回答

3

可以使用依賴註解即使在servlet的(有一個特殊的SpringBeanAutowiringSupport輔助類此pourpose)注:

public class CustomServlet extends HttpServlet { 

    @Autowired 
    private ProductService productService; 

    @Override 
    public void init(ServletConfig config) throws ServletException { 
     super.init(config); 
     // inject productService dependency 
     SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 
    } 

    .... 

} 
+0

感謝您的回覆和示例,我試過了,但我仍然得到空值。當我使用ClassPathXmlApplicationContext獲取上下文時,我的工作更早,但理想情況下,我想將Bean注入Servlet。我有可能從應用程序上下文中錯誤地導出它嗎?謝謝,O. – user676567

+0

我不熟悉'ServletContextAttributeExporter',所以我不能告訴你。但是我注意到了暴露的鍵'SpaceReaderKey'和代碼'getServletContext()。getAttribute(「SpaceReader」)''中使用的區別。可能它一定是一樣的嗎? –