Spring - セッションリスナーで依存関係注入を行う方法

Spring –セッションリスナーで依存性注入を行う方法

Springには「ContextLoaderListener」リスナーが付属しており、セッションリスナーへのSpring依存性注入を有効にします。 このチュートリアルでは、Spring依存性注入Beanをセッションリスナーに追加することにより、このHttpSessionListener exampleを修正します。

1. 春豆

作成されたセッションの総数を印刷する単純なカウンターサービスを作成します。

ファイル:CounterService.java

package com.example.common;

public class CounterService{

    public void printCounter(int count){
        System.out.println("Total session created : " + count);
    }

}

File : counter.xml –Bean構成ファイル。



    

2. WebApplicationContextUtils

WebApplicationContextUtils」を使用してSpringのコンテキストを取得します。後で、宣言されたSpringのBeanを通常のSpringの方法で取得できます。

ファイル:SessionCounterListener.java

package com.example.common;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SessionCounterListener implements HttpSessionListener {

     private static int totalActiveSessions;

     public static int getTotalActiveSession(){
           return totalActiveSessions;
     }

    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
           totalActiveSessions++;
           System.out.println("sessionCreated - add one session into counter");
           printCounter(arg0);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
           totalActiveSessions--;
           System.out.println("sessionDestroyed - deduct one session from counter");
           printCounter(arg0);
    }

    private void printCounter(HttpSessionEvent sessionEvent){

          HttpSession session = sessionEvent.getSession();

          ApplicationContext ctx =
                WebApplicationContextUtils.
                      getWebApplicationContext(session.getServletContext());

          CounterService counterService =
                      (CounterService) ctx.getBean("counterService");

          counterService.printCounter(totalActiveSessions);
    }
}

3. 統合

唯一の問題は、WebアプリケーションがSpring Bean構成ファイルをロードする場所をどのように知るかです。 秘密は「web.xml」ファイル内にあります。

  1. ContextLoaderListener」を最初のリスナーとして登録して、WebアプリケーションにSpringコンテキストローダーを認識させます。

  2. contextConfigLocation」を構成し、SpringのBean構成ファイルを定義します。

ファイル:web.xml




  Archetype Created Web Application

  
    contextConfigLocation
    /WEB-INF/Spring/counter.xml
  

  
        
            org.springframework.web.context.ContextLoaderListener
        
  

  
    
            com.example.common.SessionCounterListener
        
  

  
    Spring DI Servlet Listener
    com.example.common.App
  

  
    Spring DI Servlet Listener
    /Demo
  

ファイル:App.java

package com.example.common;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class App extends HttpServlet{

  public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException{

        HttpSession session = request.getSession(); //sessionCreated() is executed
        session.setAttribute("url", "example.com");
        session.invalidate();  //sessionDestroyed() is executed

        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("

Spring Dependency Injection into Servlet Listenner

"); out.println(""); out.println(""); } }

Tomcatを起動し、URL「http://localhost:8080/SpringWebExample/Demo」にアクセスします。

出力

sessionCreated - add one session into counter
Total session created : 1
sessionDestroyed - deduct one session from counter
Total session created : 0

コンソール出力を確認し、Spring DIを介してカウンターサービスBeanを取得し、セッションの合計数を出力します。

結論

Springでは、「ContextLoaderListener」はintegrate Spring Dependency Injection to almost all of the web applicationへの一般的な方法です。

ダウンロード