前言
有时启动SpringBoot项目后需要自运行函数来满足一些项目需求,下面介绍三种方式以此实现。
一、定义实体类实现ApplicationRunner接口
@Component
public class Demo implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception{
Systom.out.println("测试");
}
}
二、定义实体类实现CommandLineRunner接口
@Component
public class Demo implements CommandLineRunner{
@Override
public void run(String... args) throws Exception{
Systom.out.println("测试");
}
}
底层实现逻辑
SpringApplication的run方法执行时会运行afterRefresh方法
afterRefresh方法内部会执行callRunners方法
callRunners会检索实现ApplicationRunner、CommandLineRunner 接口的类,并调用重写方法。
Original: https://www.cnblogs.com/nhdlb/p/15917897.html
Author: 怒吼的萝卜
Title: SpringBoot:SpringBoot项目启动后立即执行函数的两种方式
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/540999/
转载文章受原作者版权保护。转载请注明原作者出处!