因项目需要预配置 文件加载路径,需要在项目启动完成后对配置文件所在的目录进行初始化。
下面简单说一说在SpringBoot中该如何去实现。
第一步 创建实现ApplicationListener接口的类
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent>{
private static final Log logger = LogFactory.getLog(ApplicationStartup.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
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();
}
}
}
我们的代码和逻辑需要写在onApplicationEvent方法中,其中ContextRefreshedEvent是Spring的ApplicationContextEvent一个实现,会在容器初始化完成后调用;
第二步 在SpringBoot中注册我们刚创建的类
@SpringBootApplication
public class Application {
public static final Log logger = LogFactory.getLog(Application.class);
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.addListeners(new ApplicationStartup());
springApplication.run(args);
}
}
这样在项目启动完成后就会调用onApplicationEvent方法来完成参数的初始化。