欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

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

来源: javaer 分享于  点击 45238 次 点评:3

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


目录
  • 1、实现 CommandLineRunner 接口
  • 2、实现 ApplicationRunner 接口
  • 3、实现 ApplicationListener 接口
  • 4、@PostConstruct 注解
  • 5、实现 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");
    }
}
  • 如果监听的是 ApplicationStartedEvent 事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之前执行;
  • 如果监听的是 ApplicationReadyEvent 事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之后执行;

顺序:

默认是 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====================");
    }

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。

您可能感兴趣的文章:
  • SpringBoot启动参数的实现
  • SpringBoot启动时运行特定代码的多种方式小结
  • SpringBoot项目启动后自动加载系统配置的多种实现方式
  • SpringBoot的两种启动方式原理解析(配置方案)
  • 如何解决springboot启动的时候required a bean of type 'XXX' not be问题
  • springboot启动流程过程
相关栏目:

用户点评