java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot启动后执行方法

SpringBoot启动后执行方法的五种实现方式

作者:sco5282

本文介绍了SpringBoot中五种在项目启动后执行方法的方式,包括实现CommandLineRunner和ApplicationRunner接口、实现ApplicationListener接口、使用@PostConstruct注解以及实现InitializingBean接口,每种方式都有其特点和适用场景

在 SpringBoot 工程 启动后, 执行方法的五种方式:

1、实现 CommandLineRunner 接口

项目初始化完毕后,才会调用方法,提供服务

@Component
public class StartInit2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner====================");
    }
}

2、实现 ApplicationRunner 接口

同 CommandLineRunner。只是传参格式不一样。CommandLineRunner:没有任何限制;ApplicationRunner:key-value

@Component
public class StartInit3 implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("ApplicationRunner=================");
    }
}

3、实现 ApplicationListener 接口

项目初始化完毕后,才会调用方法,提供服务。注意监听的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能无法注入 bean。

@Component
public class StartInit4 implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("ApplicationListener================ApplicationStartedEvent");
    }
}

顺序:

默认是 ApplicationRunner 先执行,如果双方指定了@Order 则按照 @Order的大小顺序执行,小的先执行。

原理:

  1. SpringApplication 的run方法会执行afterRefresh方法。
  2. afterRefresh方法会执行callRunners方法。
  3. callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法

4、@PostConstruct 注解

在项目初始化过程中,就会调用此方法。如果业务逻辑执行很耗时,可能会导致项目启动失败。

@Component
public class StartInit {

    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct===============================");
    }

}

5、实现 InitializingBean 接口

项目启动时,调用此方法

@Component
public class StartInit6 implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        System.out.println("InitializingBean====================");
    }

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文