实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。
为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。
很简单,只需要一个类就可以,无需其他配置。
创建实现接口 CommandLineRunner 的类
@Component
public class StartupLoading implements CommandLineRunner{
@Autowired
private RedisService redisService;
private static SecureRandom ran = new SecureRandom();
private static Logger logger = Logger.getLogger(Application.class);
@Value("${img.temp.path}")
private String imgTempPath;
@Value("${img.temp.source}")
private String imgSourcePath;
@Override
public void run(String... var1) throws Exception{
logger.info("picture creation program start...");
//如果不存在缓存数据
if(!redisService.exists("imageList")){
List<ImageAttributes> imageList = CommonMethodUtil.createImgList(imgSourcePath, imgTempPath);
//维护图像属性的list放缓存
redisService.putObject("imageList", imageList,600000L);
}
logger.info("picture creation program end...");
}
}
Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。@Order(value=1)