java - 依赖注入(inject) servlet 监听器

标签 java spring dependency-injection stripes

在我的 Stripes 应用中,我定义了以下类:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

这个应用程序的服务层使用 Spring 在 XML 文件中定义和连接一些服务 bean。我想将实现 SomeServiceAnotherService 的 bean 注入(inject)到 MyServletListener 中,这可能吗?

最佳答案

这样的事情应该可以工作:

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    @Autowired
    private SomeService someService;        
    @Autowired
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) {
        WebApplicationContextUtils
            .getRequiredWebApplicationContext(sce.getServletContext())
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    }

    ...
}

你的监听器应该在 web.xml 中 Spring 的 ContextLoaderListener 之后声明。

关于java - 依赖注入(inject) servlet 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511152/

相关文章:

java - Mahout 在行动 : Chapter 06: Wikipedia job fails with java. lang.ArrayIndexOutOfBoundsException

java - SQLite问题: database file is locked

java.lang.ClassNotFoundException : org. springframework.ui.ModelMap 错误

java - spring3 - 改变 Action 方法

c# - 使用 CaSTLe Windsor 在基类中注入(inject)原始属性

java - 使用 SwingUtilities.invokeLater() 时保留实例变量值

java - 将 Zip 转换为存储压缩

java - Spring Hibernate 保存/提交事务而不调用 Save 方法

c# - 如何在 C# 中注入(inject)类(不是接口(interface))?

c# - Autofac单例处理