在 Spring boot 项目启动时预载数据的四种方法
最编程
2024-03-09 10:00:12
...
spring boot项目启动时预加载数据的四种方式
四种方式简单实现 springboot 项目启动 预先加载数据
在工作中,我们总会有一些需要在项目启动时做一些初始化操作,比如,提前加载数据库中的一些配置到缓存中、初始化线程池等。那么我们可以使用下面几种方式之一实现初始化的操作。
一、使用@PostConstruct注解
@Slf4j
@Component
public class LunaPostConstruct {
@Autowired
private AppPolicyService appPolicyService;
@PostConstruct
public void init() {
// 在这里已经拿到数据库中的值了
List<AppPolicy> appPolicies = appPolicyService.findAll();
log.info("预加载的第一种方式-----LunaPostConstruct------");
}
}
二、使用ApplicationListener监听器,spring刷新容器完成
@Component
@Slf4j
public class LunaApplicationListener implements
ApplicationListener<ContextRefreshedEvent>
{
@Autowired
private AppPolicyService appPolicyService;
/**
* 项目启动时,调用ConfigurableApplicationContext接口上的refresh()方法将需要预先加载的数据提前加载出来
* @param contextRefreshedEvent
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
List<AppPolicy> appPolicies = appPolicyService.findAll();
// 在初始化或刷新ApplicationContext时发布,(通过使用ConfigurableApplicationContext接口上的refresh()方法)
// 这里的"已初始化"是指所有的Bean都已加载,检测到并激活了后处理器Bean
// 这里的 appPolicyService 已经加载到了
log.info("预加载的第二种方式-----LunaApplicationListener的ContextRefreshedEvent事件,appPolicyService:{}------", appPolicyService);
}
}
三、实现CommandLineRunner
- 多个类实现CommandLineRunner时,@Order(2)可以指定加载的先后顺序
- 此时运行这个jar命令如下:java -jar luna 参入一个参数:luna
@Component
@Slf4j
@Order(2)
public class LunaCommandLineRunner1 implements CommandLineRunner {
@Autowired
private AppPolicyService appPolicyService;
@Override
public void run(String... args) throws Exception {
List<AppPolicy> appPolicies = appPolicyService.findAll();
log.info("预加载的第三种方式-----LunaCommandLineRunner1------order:2");
}
}
/**
* 项目启动预先加载
* 第三种方式
* 针对的是容器初始化完成的
* @author luona
* @date 2/8/23 1:54 PM
*/
@Component
@Slf4j
@Order(1)
public class LunaCommandLineRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("预加载的第三种方式-----LunaCommandLineRunner2------order:1");
}
}
四、实现ApplicationRunner
- 第三种跟第四种基本差不多,ApplicationRunner和CommandLineRunner都是Spring Boot 提供的,相对于CommandLineRunner来说对于控制台传入的参数封装更好一些,可以通过键值对来获取指定的参数,比如--version=1.0.0
- 此时运行这个jar命令如下:java -jar luna.jar --version=1.0.0 luna ,以上命令传入了四个参数,一个键值对version=2.1.0,另就是luna。
- 同样可以通过@Order()指定优先级
@Slf4j
@Component
public class LunaApplicationRunner implements ApplicationRunner {
@Autowired
private AppPolicyService appPolicyService;
@Override
public void run(ApplicationArguments args) throws Exception {
List<AppPolicy> appPolicies = appPolicyService.findAll();
log.info("预加载的第四种方式-----LunaApplicationRunner------");
}
}
项目启动后的执行结果:
- 上面四种方式启动后的顺序
总结:
方案有很多,这里只是列举几种比较常见常用的方式。