import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ListenerConfig {
@Bean
public ApplicationStartup applicationStartListener(){
return new ApplicationStartup();
}
}
方式二
SpringBoot的启动方法中添加
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.addListeners(new ApplicationStartup());
springApplication.run(args);
}
--
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class EmbeddedServletContainerInitializedEventListener
implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
EmbeddedWebApplicationContext context = event.getApplicationContext();
Service service = context.getBean(AttendanceService.class);
// do something
// stop
context.getEmbeddedServletContainer().stop();
}
}
添加监听器到SpringBoot
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ListenerConfig {
// @Bean
// public ApplicationStartup applicationStartListener(){
// return new ApplicationStartup();
// }
@Bean
public EmbeddedServletContainerInitializedEventListener embeddedServletContainerInitializedEventListener(){
return new EmbeddedServletContainerInitializedEventListener();
}
}
原理
主要使用
ApplicationListener<ContextRefreshedEvent>
来达到启动后执行的目的向SpringBoot中添加Listener的方法有如下三种方式
方式一
config类中添加
方式二
SpringBoot的启动方法中添加
方式三
properties文件中添加
stop SpringBoot应用
使用EmbeddedServletContainerInitializedEvent事件
定义监听器
添加监听器到SpringBoot
参考