从Servlet访问Springbean

从Servlet访问Springbean,spring,Spring,我在applicationContext中定义了一个Springbean,如: <bean id="spaceReader" class="com.company.SpaceReader"> </bean> 我尝试使用以下方法导出它: <bean id="ContextExporter" class="org.springframework.web.context.support.ServletContextAttributeExporter"> &

我在applicationContext中定义了一个Springbean,如:

<bean id="spaceReader" class="com.company.SpaceReader">
</bean>
我尝试使用以下方法导出它:

<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中访问它时,我是否遗漏了一些东西?

即使在Servlet中,也可以使用注释注入依赖项(对于这个pourpose,有一个特殊的
SpringBeanAutowiringSupport
helper类):


您甚至可以在servlet中使用注释注入依赖项(对于此应用程序,有一个特殊的
SpringBeanAutowiringSupport
helper类):


添加显示如何尝试从servlet上下文检索bean的代码。spaceReader=(spaceReader)getServletContext().getAttribute(“spaceReader”);您的代码是否可能使用小写的local ref?spaceReader=(spaceReader)getServletContext().getAttribute(“spaceReader”);-添加显示如何尝试从servlet上下文检索bean的代码。spaceReader=(spaceReader)getServletContext().getAttribute(“spaceReader”);您的代码是否可能使用小写的local ref?spaceReader=(spaceReader)getServletContext().getAttribute(“spaceReader”);-谢谢你的回复和例子,我试过了,但仍然得到一个空值。我之前在使用ClassPathXmlApplicationContext获取上下文时让它工作,但理想情况下,我希望将Bean注入Servlet。我是否可能从应用程序上下文中错误地导出它?谢谢,O。我不熟悉ServletContextAttributeExporter,所以我不能告诉你。但是我注意到公开的key
SpaceReaderKey
和在code
getServletContext()中使用的key之间有一个区别。可能一定是一样的?谢谢你的回答和例子,我试过了,但还是得到了一个空值。我之前在使用ClassPathXmlApplicationContext获取上下文时让它工作,但理想情况下,我希望将Bean注入Servlet。我是否可能从应用程序上下文中错误地导出它?谢谢,O。我不熟悉ServletContextAttributeExporter,所以我不能告诉你。但是我注意到公开的key
SpaceReaderKey
和在code
getServletContext()中使用的key之间有一个区别。也许一定是一样的?
<bean id="ContextExporter" class="org.springframework.web.context.support.ServletContextAttributeExporter">
    <property name="contextExporterAttributes">
        <map>
            <entry key="SpaceReaderKey">
            <ref local="spaceReader" />
        </entry>
        </map>
    </property>
</bean>
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);
   }

   ....

}