依赖注入servlet侦听器 [英] dependency inject servlet listener

查看:100
本文介绍了依赖注入servlet侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Stripes app I define the following class:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

服务层该应用程序使用Spring来定义和连接XML文件中的某些服务bean。我想将实现 SomeService AnotherService 的bean注入到 MyServletListener ,这是可能的吗?

The service layer of this app uses Spring to define and wire together some service beans in an XML file. I would like to inject the beans that implement SomeService and AnotherService into MyServletListener, is this possible?

推荐答案

这样的东西应该可以工作:

Something like this should work:

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 之后声明。

Your listener should be declared after Spring's ContextLoaderListener in web.xml.

这篇关于依赖注入servlet侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆