如何使用 Spring 将依赖项注入 HttpSessionListener? [英] How to inject dependencies into HttpSessionListener, using Spring?

查看:39
本文介绍了如何使用 Spring 将依赖项注入 HttpSessionListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将依赖注入HttpSessionListener,使用Spring而不调用,比如context.getBean("foo-bar")?

How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar") ?

推荐答案

由于 Servlet 3.0 ServletContext 有一个addListener"方法,而不是在 web.xml 文件中添加你的监听器,你可以通过如下代码添加:

Since the Servlet 3.0 ServletContext has an "addListener" method, instead of adding your listener in your web.xml file you could add through code like so:

@Component
public class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext instanceof WebApplicationContext) {
            ((WebApplicationContext) applicationContext).getServletContext().addListener(this);
        } else {
            //Either throw an exception or fail gracefully, up to you
            throw new RuntimeException("Must be inside a web application context");
        }
    }           
}

这意味着您可以正常注入到MyHttpSessionListener"中,这样​​,只要应用程序上下文中存在 bean 就会导致侦听器注册到容器中

which means you can inject normally into the "MyHttpSessionListener" and with this, simply the presence of the bean in your application context will cause the listener to be registered with the container

这篇关于如何使用 Spring 将依赖项注入 HttpSessionListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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