26

Spring を使用して呼び出しなしで、依存関係を HttpSessionListener に注入する方法はcontext.getBean("foo-bar")?

4

3 に答える 3

30

Servlet 3.0 ServletContext には「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」に注入できます。これにより、アプリケーションコンテキストに Bean が存在するだけで、リスナーがコンテナーに登録されます。

于 2013-01-02T22:17:35.090 に答える
8

次のように、Spring コンテキストで Bean として宣言し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);
    }

    ...
}
于 2010-03-12T14:41:35.670 に答える
1

Spring 4.0 だけでなく 3 でも動作するので、以下に詳述する例を実装し、 https://stackoverflow.com/a/19795352/2213375ApplicationListener<InteractiveAuthenticationSuccessEvent>をリッスンして注入しました。HttpSession

于 2015-07-01T16:02:30.767 に答える