springboot实战笔记(七 )----springboot整合Listener

一 前言

  在以往的web.xml方式中,我们是通过以下形式进行配置Listener的:


 	com.bjsxt.listener.FirstListener

但是在springboot整合Listener可以通过以下的两种方式,

  •  通过注解扫描完成 Listener  组件的注册
  •  通过方法完成 Listener  组件的注册

pom.xml:


  4.0.0
  
    org.springframework.boot
    spring-boot-starter-parent
    1.5.10.RELEASE
  
  com.bjsxt
  04-spring-boot-Listener
  0.0.1-SNAPSHOT
  
  
  
  	1.7
  
  
  
    
        org.springframework.boot
        spring-boot-starter-web
    

二 注解扫描方式

1.编写 Listener类

package com.bjsxt.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
 * springBoot整合Listener
 */
@WebListener
public class FirstListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("Listener...init......");

	}

}

2.编写启动类

package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

/**
 * springBoot整合Listener方式一
 */
@SpringBootApplication
@ServletComponentScan
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

 

三 方法方式

1.编写Listener类

package com.bjsxt.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
 * springBoot整合Listener方式二。
 *
 *
 */
public class SecondListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("SecondListener..init.....");
	}

}

2.编写启动类

package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.bjsxt.listener.SecondListener;

/**
 * SpringBoot整合Listener方式二
 *
 *
 */
@SpringBootApplication
public class App2 {

	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);

	}
	/**
	 * 注册listener
	 */
	@Bean
	public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
		ServletListenerRegistrationBean bean= new ServletListenerRegistrationBean(new SecondListener());
		return bean;
	}
}

 

你可能感兴趣的:(spring,boot)