SpringBoot使用spring.factories加載默認配置的實現(xiàn)代碼
在日常開發(fā)過程中,發(fā)布一些產品或者框架時,會遇到某些功能需要一些配置才能正常運行,這時我們需要的提供默認配置項,同時用戶也能覆蓋進行個性化
創(chuàng)建Initializer
public class FrameContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("FrameContextInitializer--Start");
System.out.println("FrameContextInitializer--End");
}
}
配置Initializer
resources/META-INF文件夾下創(chuàng)建spring.factories文件,指定實現(xiàn)類
org.springframework.context.ApplicationContextInitializer=com.haopan.frame.common.initializer.FrameContextInitializer
實現(xiàn)Initializer
讀取默認yml文件
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;
}
將yml內容加到環(huán)境上下文
這邊的addLast是執(zhí)行順序為最后讀取,如果項目的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");
到此這篇關于SpringBoot使用spring.factories加載默認配置的實現(xiàn)代碼的文章就介紹到這了,更多相關SpringBoot spring.factories加載配置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java Spring JdbcTemplate基本使用詳解
JDBC已經能夠滿足大部分用戶最基本的需求,但是在使用JDBC時,必須自己來管理數據庫資源如:獲取PreparedStatement,設置SQL語句參數,關閉連接等步驟2021-10-10
微服務Spring?Boot?整合Redis?阻塞隊列實現(xiàn)異步秒殺下單思路詳解
這篇文章主要介紹了微服務Spring?Boot?整合Redis?阻塞隊列實現(xiàn)異步秒殺下單,使用阻塞隊列實現(xiàn)秒殺的優(yōu)化,采用異步秒殺完成下單的優(yōu)化,本文給大家分享詳細步驟及實現(xiàn)思路,需要的朋友可以參考下2022-10-10

