新建一个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