新建一個ApplicationContextListener.javajava
package com.wangxh.email.listener; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.boot.context.event.ApplicationPreparedEvent; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.*; import org.springframework.context.event.*; import org.springframework.core.style.ToStringCreator; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; public class ApplicationContextListener implements ApplicationListener { ApplicationContext applicationContext; MailProperties mailProperties; ServerProperties serverProperties; @Override public void onApplicationEvent(ApplicationEvent event) { // 在這裏能夠監聽到Spring Boot的生命週期 if (event instanceof ApplicationEnvironmentPreparedEvent) { System.out.println("初始化環境變量:ApplicationEnvironmentPreparedEvent"); // 初始化環境變量 } else if (event instanceof ApplicationPreparedEvent) { System.out.println("初始化完成:ApplicationPreparedEvent"); // 初始化完成 } else if (event instanceof ContextRefreshedEvent) { System.out.println("應用刷新:ContextRefreshedEvent"); applicationContext= ((ContextRefreshedEvent) event).getApplicationContext(); mailProperties=applicationContext.getBean(MailProperties.class); serverProperties=applicationContext.getBean(ServerProperties.class); System.out.println("serverProperties:"+ToStringBuilder.reflectionToString(serverProperties)); System.out.println("mailProperties:"+ ToStringBuilder.reflectionToString(mailProperties)); // 應用刷新 } else if (event instanceof ApplicationReadyEvent) { System.out.println("應用已啓動完成:ApplicationReadyEvent"); // 應用已啓動完成 } else if (event instanceof ContextStartedEvent) { System.out.println("應用啓動,須要在代碼動態添加監聽器纔可捕獲:ContextStartedEvent"); // 應用啓動,須要在代碼動態添加監聽器纔可捕獲 } else if (event instanceof ContextStoppedEvent) { System.out.println("應用中止:ContextStoppedEvent"); // 應用中止 } else if (event instanceof ContextClosedEvent) { System.out.println("應用關閉:ContextClosedEvent"); // 應用關閉 } } }
在application.properties文件中配置以下:web
context.listener.classes=com.wangxh.email.listener.ApplicationContextListener
這裏配置了自定義的監聽器的位置。spring
使用此監聽器能夠在ContextRefreshedEvent事件完成後執行如下準備工做,在ContextStoppedEvent或者ContextCloseEvent事件以前執行收尾工做。apache