Pregunta

Cómo inyectar dependencias en HttpSessionListener, utilizando Spring y sin llamadas, como context.getBean("foo-bar")?

¿Fue útil?

Solución

Desde el ServletContext Servlet 3.0 tiene un método "addListener", en lugar de añadir a su oyente en su archivo web.xml se podría añadir a través del código de esta manera:

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

que significa que puede inyectar normalmente en el "MyHttpSessionListener" y con ello, basta con la presencia del frijol en el contexto de la aplicación hará que el oyente a estar registrados en el contenedor

Otros consejos

Se puede declarar su HttpSessionListener como un grano en el contexto de la primavera, y registrar un proxy delegación como un oyente real en web.xml, algo como esto:

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

    ...
}

Con Spring 4.0, pero también funciona con 3, he implementado el ejemplo se detalla a continuación, escuchar ApplicationListener<InteractiveAuthenticationSuccessEvent> e inyectar el HttpSession href="https://stackoverflow.com/a/19795352/2213375"> https: // stackoverflow.com/a/19795352/2213375

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top