Spring - Как сделать внедрение зависимостей в слушателе сеанса

Spring - Как сделать внедрение зависимостей в слушателе сеанса

Spring поставляется с прослушивателем «ContextLoaderListener» для включения внедрения зависимостей Spring в прослушиватель сеанса. В этом руководстве он изменяет этотHttpSessionListener example, добавляя bean-компонент Spring для инъекции в прослушиватель сеанса.

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, а позже вы можете получить любой объявленный bean-компонент Spring обычным способом 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. интеграция

Единственная проблема заключается в том, как ваше веб-приложение знает, куда загрузить файл конфигурации бина Spring Секрет находится внутри файла «web.xml».

  1. Зарегистрируйте «ContextLoaderListener» в качестве первого слушателя, чтобы ваше веб-приложение узнало о загрузчике контекста Spring.

  2. Настройте «contextConfigLocation» и определите файл конфигурации вашего компонента Spring.

Файл: 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 и напечатаете общее количество сеансов.

Заключение

В Spring «ContextLoaderListener» - это общий способ перехода кintegrate Spring Dependency Injection to almost all of the web application.

Скачать