目录
分享一下自己用过的java程序初始化启动自动执行的三种方法
@PostConstruct注解
将此注解加在要执行的方法上,则程序初始化启动的时候,会执行此方法,一般用来初始化必要的程序初始信息
注意:加了postconstruct注解的方法,如果执行失败,整个程序会无法正常启动!这个方法执行不完,整个程序也启动不了!!!
详情请看我的错误总结 开发错误总结---@PostConstruct注解导致的程序无法启动(@PostConstruct的执行)_是菜菜的小严惜哎的博客-CSDN博客
开始试验:
启动类
@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接口程序初始化");
}
}
执行一下来看效果