Java程序初始化启动自动执行的三种方式
作者:是菜菜的小严惜哎
这篇文章主要介绍了Java程序初始化启动自动执行的三种方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java程序初始化启动自动执行的三种方式
@PostConstruct注解
将此注解加在要执行的方法上,则程序初始化启动的时候,会执行此方法,一般用来初始化必要的程序初始信息
注意:
加了postconstruct注解的方法,如果执行失败,整个程序会无法正常启动!这个方法执行不完,整个程序也启动不了!!!
详情请看我的错误总结 开发错误总结---@PostConstruct注解导致的程序无法启动(@PostConstruct的执行)
开始试验:
- 启动类
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
}- 测试类
@Service
@Slf4j
public class PostConstructTest {
@PostConstruct
public void testPostConstruct () {
log.info("程序初始化执行");
}
}- 启动看效果

CommandLineRunner接口
- 实现 CommandLineRunner接口
@Slf4j
@Component
public class InitCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("实现CommandLineRunner接口的程序初始化");
}
}- 启动看效果

ApplicationRunner 接口
- 实现 ApplicationRunner 接口
@Component
@Slf4j
public class InitApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("实现ApplicationRunner接口程序初始化");
}
}- 启动看效果

@Order注解设置启动顺序
我们给前两个实现ApplicationRunner 接口和CommandLineRunner 接口的启动类设置启动顺序
- 为了让效果明显一点,我们让程序执行完第一个之后睡眠一下
@Slf4j
@Component
@Order(value = 1)
public class InitCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("实现CommandLineRunner接口的程序初始化");
Thread.sleep(2000);
}
}@Component
@Slf4j
@Order(value = 2)
public class InitApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("实现ApplicationRunner接口程序初始化");
}
}- 执行一下来看效果

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