yankj12 / blog

技术研究、管理实践、其他的一些文章
MIT License
1 stars 2 forks source link

Spring Boot启动后执行特定操作,然后自动停止 #59

Open yankj12 opened 5 years ago

yankj12 commented 5 years ago

原理

主要使用ApplicationListener<ContextRefreshedEvent>来达到启动后执行的目的

向SpringBoot中添加Listener的方法有如下三种方式

方式一

config类中添加


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); 
}
--

方式三

properties文件中添加

context.listener.classes=com.sinosoft.listener.ApplicationStartupListener

stop SpringBoot应用

使用EmbeddedServletContainerInitializedEvent事件

定义监听器

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();
    }
}

参考