Рубрики
Без рубрики

Весна – Как сделать инъекцию зависимостей в прослушивателе сеанса

– Весна – Как сделать инъекцию зависимостей в прослушивателе сеанса

Spring поставляется с прослушивателем ” ContextLoaderListener “, чтобы включить внедрение зависимостей Spring в sessionlistener. В этом уроке он пересматривает это Пример HttpSessionListener путем добавления компонента Spring-зависимости в прослушиватель сеанса.

1. Весенние Бобы

Создайте простую службу счетчиков для печати общего количества созданных сеансов.

Файл: CounterService.java

package com.mkyong.common;
 
public class CounterService{
 
	public void printCounter(int count){
		System.out.println("Total session created : " + count);
	}

}

Файл: counter.xml – Файл конфигурации компонента.




	
	

2. Веб-приложения-контекстуалы

Использует ” WebApplicationContextUtils ” для получения контекста Spring, а позже вы можете получить любой объявленный компонент Spring обычным способом Spring.

Файл: SessionCounterListener.java

package com.mkyong.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 bean? Секрет находится внутри”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.mkyong.common.SessionCounterListener
        
  

  
	Spring DI Servlet Listener
	com.mkyong.common.App
  
 
  
	Spring DI Servlet Listener
	/Demo
  
  

Файл: App.java

package com.mkyong.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", "mkyong.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 и выводите общее количество сеансов.

Вывод

Весной ” ContextLoaderListener ” – это универсальный способ интегрировать внедрение зависимостей Spring почти во все веб-приложения .

Скачать

Оригинал: “https://mkyong.com/spring/spring-how-to-do-dependency-injection-in-your-session-listener/”