在日常开发过程中,发布一些产品或者框架时,会遇到某些功能需要一些配置才能正常运行,这时我们需要的提供默认配置项,同时用户也能覆盖进行个性化
public class FrameContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("FrameContextInitializer--Start");
System.out.println("FrameContextInitializer--End");
}
}
resources/META-INF文件夹下创建spring.factories文件,指定实现类
org.springframework.context.ApplicationContextInitializer=com.haopan.frame.common.initializer.FrameContextInitializer
String frameYAMLFilePath = ClassPathFileUtil.getFilePathActual("systemfile/config/frame.yml");
public static String getFilePathActual(String classFilePath) {
String filePath = "";
try {
String templateFilePath = "tempfiles/classpathfile/";
File tempDir = new File(templateFilePath);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
String[] filePathList = classFilePath.split("/");
String checkFilePath = "tempfiles/classpathfile";
for (String item : filePathList) {
checkFilePath += "/" + item;
}
File tempFile = new File(checkFilePath);
if (tempFile.exists()) {
tempFile.delete();
}
//解析
ClassPathResource classPathResource = new ClassPathResource(classFilePath);
InputStream inputStream = classPathResource.getInputStream();
checkFilePath = "tempfiles/classpathfile";
for (int i = 0; i < filePathList.length; i++) {
checkFilePath += "/" + filePathList[i];
if (i == filePathList.length - 1) {
//文件
File file = new File(checkFilePath);
if(!file.exists()){
FileUtils.copyInputStreamToFile(inputStream, file);
}
} else {
//目录
tempDir = new File(checkFilePath);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
}
}
inputStream.close();
filePath = checkFilePath;
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
这边的addLast是执行顺序为最后读取,如果项目的yml文件没有读取到,则默认配置是一个保底
System.out.println("FrameContextInitializer--Start");
PropertySource<?> propertySource = loader.load("frameConfiguration", new InputStreamResource(new FileInputStream(frameYAMLFilePath))).get(0);
applicationContext.getEnvironment().getPropertySources().addLast(propertySource);
System.out.println("FrameContextInitializer--End");