java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot启动执行特定代码

在SpringBoot启动时执行特定代码的常见方法小结

作者:yifanghub

本文总结了SpringBoot启动时执行代码的5种方法,涵盖@PostConstruct、CommandLineRunner、ApplicationRunner、ApplicationListener及@EventListener,各方法适用于不同场景,需要的朋友可以参考下

在SpringBoot的项目中,经常会遇到需要在项目启动后执行一些操作的情形,如加载配置,初始化数据,缓存预热等,本文整理了几种常见的在项目启动时执行特定代码的方法。

1.使用 @PostConstruct 注解

@Slf4j
@Component
public class MyInit {

    @PostConstruct
    public void init() {
        log.info("PostConstruct initialized~~~");
    }

}

优点:

缺点:

2.使用 CommandLineRunner 接口

CommandLineRunner 接口提供了一个 run 方法,该方法会在Spring Boot应用启动后执行。

@Component
@Slf4j
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("MyStartupRunner CommandLineRunner initialized~~~");
    }
}

优点:

缺点:

3.使用 ApplicationRunner 接口

ApplicationRunner 接口与 CommandLineRunner 类似,但它提供了更丰富的 ApplicationArguments 参数来处理命令行参数。

@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("MyApplicationRunner initialized~~~");
    }
}

优点:

缺点:

4.使用 ApplicationListener 监听 ApplicationReadyEvent

@Component
@Slf4j
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("MyApplicationListener initialized~~~");
    }
}

优点:

缺点:

5.@EventListener监听ApplicationReadyEvent

可以使用 @EventListener 注解来监听 ApplicationReadyEvent 事件

@Component
@Slf4j
public class MyEventListener {
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("MyEventListener initialized~~~");
    }
}

优点:

缺点:

以上几种方式执行后日志打印如下:

[main] com.example.springdemo.init.MyInit       : PostConstruct initialized~~~
[main] c.e.springdemo.SpringDemoApplication     : Started SpringDemoApplication in 0.358 seconds (JVM running for 0.809)
[main] c.e.springdemo.init.MyApplicationRunner  : MyApplicationRunner initialized~~~
[main] c.e.springdemo.init.MyCommandLineRunner  : CommandLineRunner initialized~~~
[main] c.e.s.init.MyApplicationListener         : MyApplicationListener initialized~~~
[main] c.e.springdemo.init.MyEventListener      : MyEventListener initialized~~~

总结

以上就是在SpringBoot启动时执行特定代码的常见方法小结的详细内容,更多关于SpringBoot启动执行特定代码的资料请关注脚本之家其它相关文章!

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