从Servlet访问Spring Bean

时间:2013-07-05 12:35:48

标签: spring

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

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

我希望能够在我的Application 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时,它返回一个Null值。只是想知道当我导出Bean或者当我尝试在Servlet中访问它时,我是否缺少某些东西?

1 个答案:

答案 0 :(得分:4)

即使在servlet中也可以使用注释注入依赖项(这个pourpose有一个特殊的SpringBeanAutowiringSupport帮助器类):

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);
   }

   ....

}
相关问题