質問

context.getBean("foo-bar")のように、春と呼び出しなしを使用して、のHttpSessionListenerへの依存性を注入する方法は?

役に立ちましたか?

解決

サーブレット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の存在がリスナーを引き起こすことを意味するコンテナに登録される。

他のヒント

あなたは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);
    }

    ...
}

春4.0にも3で動作し、私はApplicationListener<InteractiveAuthenticationSuccessEvent>に耳を傾け、HttpSessionます。https:// stackoverflow.com/a/19795352/2213375する

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top