美文网首页Java Web架构设计
spring boot 系统启动事件监听

spring boot 系统启动事件监听

作者: 张艺 | 来源:发表于2017-10-13 18:11 被阅读4666次

    spring boot在启动过程中提供了一些事件的监听,这样极大的方便了开发者拓展功能;

    spring boot支持的事件类型:

    事件列表

    关键步骤:

    1、实现接口ApplicationListener来创建自己的事件监听类;如:

    @Component
    public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartingEvent> {
    
        @Override
        public void onApplicationEvent(ApplicationStartingEvent applicationStartedEvent) {
            System.out.println("application starting .....");
        }
    }
    

    2、在启动类中注册,修改此前启动类的代码为:

    @SpringBootApplication
    public class SpringBootDemoApplication {
        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
            springApplication.addListeners(new ApplicationStartedEventListener());
    
            springApplication.run(args);
        }
    }
    

    3、运行发现启动前先打印


    image.png

    同样的,为了省事,直接用lamda来实现其他几个接口

    @SpringBootApplication
    public class SpringBootDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
            springApplication.addListeners(new ApplicationStartedEventListener());
    
            springApplication.addListeners((ApplicationListener<ApplicationPreparedEvent>) event -> {
                System.out.println("application prepared event");
            });
    
            springApplication.addListeners((ApplicationListener<ApplicationReadyEvent>) event -> {
                System.out.println("application ready event");
            });
    
            springApplication.run(args);
        }
    }
    

    系统启动时,执行顺序为:application starting > application prepared > application ready

    相关文章

      网友评论

        本文标题:spring boot 系统启动事件监听

        本文链接:https://www.haomeiwen.com/subject/pdgzyxtx.html