1. 程式人生 > >SpringBoot自定義初始化Listener配置

SpringBoot自定義初始化Listener配置

SpringBoot自定義初始化Listener配置

0x01 摘要

在傳統的以Spring-Web程式中,我們會繼承ContextLoaderListener來實現一些早期執行的初始化程式碼。但是現在遷移到Spring-Boot後發現不能這麼做了。本文講講在SpringBoot中怎麼配置Listener。

0x02 ServletContextListener

ServletContextListener是依賴於Servlet容器的。

2.1 Listener配置

Listener改為實現ServletContextListener,還要在類上加@WebListener

註解。其餘可以不動:

/**
 * Created by chengc on 2018/5/7.
 */
@WebListener
public class DoveInitListener
        implements ServletContextListener
{
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //do something while contextInitialized
    }

    @Override
    public
void contextDestroyed(ServletContextEvent servletContextEvent) { //do something while contextDestroyed } }
  • contextInitialized
    用來通知監聽器web應用初始化過程已經開始。
    在所有filterservlet初始化前會通知所有實現了ServletContextListener的對監聽器。
  • contextDestroyed
    用來通知servletContext即將關閉。
    在通知所有ServletContextListener監聽器servletContext銷燬之前,所有servlet
    filter都已被銷燬。

2.2 SpringBoot啟動類配置

只需要在SpringBoot 啟動類中加上@ServletComponentScan註解即可

@ServletComponentScan
@SpringBootApplication
public class SpringbootServer extends SpringBootServletInitializer
{
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(SpringbootServer.class);
	}

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

0x03 ApplicationListener

ApplicationListener依賴於Spring。

在普通Spring應用中一般監聽ContextRefreshedEvent事件。而在Spring Boot中可以監聽多種事件,比如:

  • ApplicationStartedEvent:spring boot啟動監聽類
  • ApplicationEnvironmentPreparedEvent:環境事先準備
  • ApplicationPreparedEvent:上下文context準備時觸發
  • ApplicationReadyEvent:上下文已經準備完畢的時候觸發
  • ApplicationFailedEvent:該事件為spring boot啟動失敗時的操作

ApplicationListener一般用於spring容器初始化完成之後,執行需要處理的一些操作,比如一些資料的載入、初始化快取、特定任務的註冊等等。

示例如下:

@Service
public class AppListener implements ApplicationListener {
   @Autowired
    private UserMapper userMapper;
 
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    	//基於ApplicationListener的監聽器的onApplicationEvent方法可能會被執行多次,所以需要新增以下判斷:
        if(event.getApplicationContext().getParent() == null){
	        System.out.println("*************ApplicationListener<ContextRefreshedEvent> start************");
	 
	        User user2 = userMapper.selectByUsername("zifangsky");
	        System.out.println(JsonUtils.toJson(user2));
        }
    }

0xFF 更多參考文件

淺析servlet的ServletContextListener與Spring的ApplicationListner

Spring中的ApplicationListener和ServletContextListener的區別