SpringBoot整合listener两种方式

1.创建maven项目,导入springboot的maven依赖
pom.xml


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.2.RELEASE
	

	per.czt.04-spring-boot-listener
	04-spring-boot-listener
	0.0.1-SNAPSHOT
	jar

	04-spring-boot-listener
	http://maven.apache.org
	
		UTF-8
		1.7
	

	
		
			junit
			junit
			3.8.1
			test
		

		
		

		
		
			org.springframework.boot
			spring-boot-starter-web
		
	


方式一:通过注解扫描方式整合listener
FirstListener.Class

package per.czt.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/*
 * 
 * 		per.czt.listener.FirstListener
 * 
 * 
 * 
 * 
 * 
 */

@WebListener
public class FirstListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("FirstListener init...");

	}

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

}

SecondListener.Class
启动类:App.Class

package per.czt;

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

/**
 * Hello world!
 *
 */
@SpringBootApplication
@ServletComponentScan
public class App 
{
    public static void main( String[] args )
    {
    	
       SpringApplication.run(App.class,args);
    }
}

方式二:通过编写方法的方式整合listener
SecondListener.Class

package per.czt.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SecondListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("SecondListener init...");

	}

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

}

启动类:App2.Class

package per.czt;

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 per.czt.listener.SecondListener;

@SpringBootApplication
public class App2 {

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

	}
	@Bean
	public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
		ServletListenerRegistrationBean listener=new ServletListenerRegistrationBean(new SecondListener());
	    return listener;
	}

}

你可能感兴趣的:(SpringBoot,ServletListener)