一、前言
平常的项目开发中,经常会遇到数据初始化的需求,比如说在项目启动之后需要读取自定义的配置信息、初始化自定义对象信息等等,那springboot项目中进行初始化方式有哪些,今天就一起来聊一下.为方便小伙伴查阅,第二个章节已经将各种方式进行了实现,需要用到的小伙伴可以直接拿去用。至于为什么能那样做,翻阅了相关官方文档,会做出简要说明,感兴趣的小伙伴可以看下第三个章节。
二、springboot项目初始化方式实战篇
1.ApplicationRunner
@Component
public class PersonalApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("spring容器初始化方式:ApplicationRunner");
}
}
2.CommandLineRunner
@Component
public class PersonalCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("spring容器初始化方式:CommandLineRunner");
}
}
3.ApplicationListener监听ContextRefreshedEvent事件
@Component
public class PersonalContextRefreshedEvent implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("spring容器初始化方式:ApplicationListener<ContextRefreshedEvent>");
}
}
4.InitializingBean
@Configuration
public class PersonalInitializingBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("spring容器初始化方式:PersonalInitializingBean");
}
}
5.@PostConstruct
@Configuration
public class PersonalInitializingBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("spring容器初始化方式:PersonalInitializingBean");
}
}
6.静态代码块
@Component
public class PersonalStacticInit {
static {
System.out.println("静态代码块执行。。。。。。。。");
}
}
二、各种初始化操作的执行顺序
项目启动,控制台输出内容如下:
参考文章:
springboot项目常用的初始化方式,看看你知道几个?_springboot初始化_卖柴火的小伙子的博客-CSDN博客