在上篇文章中,我们提到了通过添加监听的方式来实现参数的初始化。此外,SpringBoot还提供了另外一种参数初始化方式,实现接口 CommandLineRunner
第一步:创建实现CommandLineRunner接口的类
@Component
@Order(value=1)
public class StartupConfig implements CommandLineRunner{
private static final Log logger = LogFactory.getLog(StartupConfig.class);
@Override
public void run(String... arg0) throws Exception {
logger.info("系统参数开始初始化....");
File directory = new File("");// 参数为空
String realPath;
try {
realPath = directory.getCanonicalPath()+File.separator+"temp";
UapReportConfiguration.getInstance().init(realPath);
new UapReportCache().init();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们只需要将我们需要初始化的参数写在run方法中,这样Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。有时候为了方便管理,需要将参数分开并规定参数的加载顺序,我们可以创建多个实现 CommandLineRunner接口的类,通过@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。