目录
1、在SpringBoot应用启动后进行初始工作的意义
在你的SpringBoot项目启动后,需要写入缓存,或者需要初始常量信息,此时需要使用到在SpringBoot Runner,实现其功能。
2、如果实现在应用启动后进行初始化操作
Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。
此两种方法是为了满足,在项目启动的后,立刻执行某些方法。
我们可以通过实现ApplicationRunner和CommandLineRunner,它们都是在SpringApplication 执行之后开始执行的。
CommandLineRunner 接口提供的方法只能传递字符串,ApplicationRunner 是使用ApplicationArguments 用来接收参数的,此方式可以自更加复杂场景使用。
使用CommandLineRunner来实现启动后执行
/**
* ApplicationRunner
* 该接口的方法会在服务启动之后被立即执行
* 主要用来做一些初始化的工作
* 但是该方法的运行是在SpringApplication.run(…) 执行完毕之前执行
*/
@Component
public class LoadConstantsAndWriteCacheRunner implements CommandLineRunner {
/**
* 会在服务启动完成后立即执行
*/
@Override
public void run(String... args) throws Exception {
System.out.println("This will be execute when the project was started!");
}
}
通过 ApplicationRunner实现的接口
@Component
public class LoadConstantsAndWriteCacheRunner implements ApplicationRunner {
/**
* 会在服务启动完成后立即执行
*/
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner will be execute when the project was started!");
}
}
这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@Component注解。
如果想要指定启动方法执行的顺序,可以通过实现
org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。
建议使用 Order注解实现方式
/**
* 此类是将spring配置信息转换成静态属性
*/
@Component
@Order(value = 1)
public class LoadConstantsAndWriteCacheRunner implements ApplicationRunner {
public static String appKey;
@Autowired
private FrameworkBaseConfig frameworkBaseConfig;
@Autowired
private RedisStringService redisStringService;
@Override
public void run(ApplicationArguments args) throws Exception {
/**
System.out.println("ApplicationRunner: "+frameworkBaseConfig.getAppKey());
appKey = frameworkBaseConfig.getAppKey();
*/
System.out.println("ApplicationRunner: "+frameworkBaseConfig.getAppKey());
appKey = frameworkBaseConfig.getAppKey();
redisStringService.set("systemNameServletWrite", "whdcmap-web");
System.out.println("ApplicationRunner initCache function!");
System.out.println("ApplicationRunner DIC_KEY:"+CacheRedisConstants.REDIS_KEYS.DIC_KEY);
}
}
3、实践截图
本人主要目的是想在系统启动完毕后实现数据字典及常量配置参数表写入到Redis缓存之中。实现如下图所示:
参考文章: