سؤال

كيفية ضخ التبعيات في httsessionlistener، باستخدام الربيع وبدون مكالمات، مثل context.getBean("foo-bar") ?

هل كانت مفيدة؟

المحلول

نظرا لأن ServletContext يحتوي Serverlet 3.0 على طريقة "AddListener"، بدلا من إضافة مستمعك في ملف Web.xml الخاص بك، يمكنك إضافة رمز مثل

@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" ومع هذا، ببساطة وجود الفول في سياق التطبيق الخاص بك سيؤدي إلى تسجيل المستمع مع الحاوية

نصائح أخرى

يمكنك إعلانك HttpSessionListener كحبة في سياق الربيع، وتسجيل وكيل وفد كمستمع حقيقي في web.xml, ، شيء من هذا القبيل:

public class DelegationListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent se) {
        ApplicationContext context = 
            WebApplicationContextUtils.getWebApplicationContext(
                se.getSession().getServletContext()
            );

        HttpSessionListener target = 
            context.getBean("myListener", HttpSessionListener.class);
        target.sessionCreated(se);
    }

    ...
}

مع الربيع 4.0 ولكن أيضا يعمل مع 3، قمت بتنفيذ المثال مفصل أدناه، والاستماع إلى ApplicationListener<InteractiveAuthenticationSuccessEvent> وحقن HttpSession https://stackoverflow.com/a/19795352/2213375.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top