Commit f9bee9b3 LN

启动前将外部配置文件复制到配置目录。

1 个父辈 1f2aea60
package com.neotel.smfcore;
import com.neotel.smfcore.common.config.CustomConfigLoader;
import com.neotel.smfcore.security.annotation.AnonymousGetMapping;
import com.neotel.smfcore.common.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
......@@ -15,6 +17,7 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@Slf4j
public class SmfCoreApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
......@@ -50,4 +53,23 @@ public class SmfCoreApplication extends SpringBootServletInitializer {
return "SMF service started successfully, version:" + version;
}
@AnonymousGetMapping( "/config/" )
public String config() {
boolean found = Boolean.parseBoolean(
System.getProperty("smfcore.external.config.found", "false"));
String externalConfigPath = System.getProperty("smfcore.external.config.path");
String msg = "";
if (found) {
msg = "Using external configuration file: " + externalConfigPath;
} else {
msg = "External configuration file not found, using internal configuration file. ";
msg += "Directories searched for external files: " + String.join(";", CustomConfigLoader.configDirs);
}
log.info(msg);
return msg;
}
}
package com.neotel.smfcore.common.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 自定义配置加载器,用于检查外部配置文件
* 在Spring Boot启动时,会检查外部配置文件是否存在
* 如果存在,则复制到classpath:/config/目录下覆盖默认配置
*/
@Slf4j
public class CustomConfigLoader implements EnvironmentPostProcessor, Ordered {
// 系统属性名,用于指定外部配置文件目录
private static final String CONFIG_DIR_PROPERTY = "smfcore.config.dir";
// 环境变量名,用于指定外部配置文件目录
private static final String CONFIG_DIR_ENV = "SMFCORE_CONFIG_DIR";
// 默认的外部配置文件目录
private static final String DEFAULT_CONFIG_DIR = "D:/smfConfig";
//C:\Program Files\Apache Software Foundation\Tomcat 9.0\config
private static String TOMCAT_CONFIG_DIR="";
// // 应用程序本地相对路径
// private static final String[] LOCAL_CONFIG_PATHS = {
// "./config",
// "."
// };
// 配置文件名
private static final String[] CONFIG_FILE_NAMES = {
"application.yml",
"application-prod.yml",
"application-dev.yml"
};
// 内部配置目录(相对于classpath)
private static final String INTERNAL_CONFIG_DIR = "config";
public static List<String > configDirs=new ArrayList<>();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
org.springframework.boot.SpringApplication application) {
boolean externalConfigFound = false;
String foundConfigPath = null;
// 获取配置目录路径
configDirs=new ArrayList<>();
configDirs = getConfigDirectories();
for (String dir : configDirs) {
boolean findOk = false;
for (String fileName : CONFIG_FILE_NAMES) {
String path = dir + "/" + fileName;
File file = new File(path);
if (file.exists() && file.isFile()) {
Log("找到外部配置文件: " + file.getAbsolutePath());
externalConfigFound = true;
foundConfigPath = dir;
// 复制配置文件到内部配置目录
try {
copyConfigFile(file, fileName);
findOk = true;
} catch (IOException e) {
Log("复制配置文件失败: " + e.getMessage());
}
}
}
if (findOk) {
break;
}
}
// 设置标志,用于显示信息
if (externalConfigFound) {
System.setProperty("smfcore.external.config.found", "true");
System.setProperty("smfcore.external.config.path", foundConfigPath);
} else {
Log("未找到外部配置文件,将使用内部配置文件");
System.setProperty("smfcore.external.config.found", "false");
}
boolean found = Boolean.parseBoolean(
System.getProperty("smfcore.external.config.found", "false"));
String externalConfigPath = System.getProperty("smfcore.external.config.path");
Log("--------------------------------");
if (found) {
Log("使用外部配置文件: " + externalConfigPath);
} else {
Log("未找到外部配置文件,使用内部配置文件");
Log("您可以通过以下方式指定外部配置文件目录:");
Log("1. 添加JVM参数: -D "+CONFIG_DIR_PROPERTY+"=<配置目录路径>");
Log("2. 设置环境变量: "+CONFIG_DIR_ENV+"=<配置目录路径>");
Log("3. 默认配置目录为: "+DEFAULT_CONFIG_DIR);
Log("4. tomcat目录下config目录: "+TOMCAT_CONFIG_DIR);
}
}
/**
* 将外部配置文件复制到内部配置目录
*/
private void copyConfigFile(File sourceFile, String fileName) throws IOException {
// 获取应用程序的WEB-INF/classes目录
String targetDir = getWebInfClassesPath() + "/" + INTERNAL_CONFIG_DIR;
// 确保目标目录存在
File targetDirFile = new File(targetDir);
if (!targetDirFile.exists()) {
targetDirFile.mkdirs();
}
// 复制文件
File targetFile = new File(targetDir + "/" + fileName);
Files.copy(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
Log("已将外部配置文件"+sourceFile.getAbsolutePath()+" 复制到 :"+targetFile.getAbsolutePath());
}
/**
* 获取WEB-INF/classes目录的路径
*/
private String getWebInfClassesPath() {
try {
// 尝试获取classpath根目录
URL url = ResourceUtils.getURL("classpath:");
String path = url.getPath();
// 处理URL编码
if (path.startsWith("/")) {
path = path.substring(1);
}
// 处理Windows路径
if (path.startsWith("/")) {
path = path.substring(1);
}
// 处理file:前缀
if (path.startsWith("file:")) {
path = path.substring(5);
}
// 处理URL编码的路径
path = java.net.URLDecoder.decode(path, "UTF-8");
Log("应用程序classpath路径: " + path);
return path;
} catch (Exception e) {
Log("获取classpath路径失败: " + e.getMessage());
// 如果无法获取classpath,则使用当前工作目录
String userDir = System.getProperty("user.dir");
Log("使用当前工作目录: " + userDir);
return userDir;
}
}
/**
* 获取Tomcat配置目录
*/
private String getTomcatConfigDir() {
// 从WEB-INF/classes路径推断Tomcat目录
String webInfClassesPath = getWebInfClassesPath();
if (webInfClassesPath != null && !webInfClassesPath.isEmpty()) {
// 检查路径是否包含WEB-INF/classes
if (webInfClassesPath.contains("WEB-INF") && webInfClassesPath.contains("classes")) {
// 提取Tomcat根目录
int webappsIndex = webInfClassesPath.indexOf("webapps");
if (webappsIndex > 0) {
String tomcatHome = webInfClassesPath.substring(0, webappsIndex);
String configDir = tomcatHome + "config";
Log("从WEB-INF/classes路径推断Tomcat配置目录: " + configDir);
TOMCAT_CONFIG_DIR = configDir;
return TOMCAT_CONFIG_DIR;
}
}
}
// 检查默认的Tomcat配置目录
String defaultPath = "C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\config";
Path configPath = Paths.get(defaultPath);
if (Files.exists(configPath)) {
Log("找到默认Tomcat配置目录: " + configPath);
TOMCAT_CONFIG_DIR = defaultPath;
return defaultPath;
}
defaultPath = "C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0";
configPath = Paths.get(defaultPath);
if (Files.exists(configPath)) {
Log("找到默认Tomcat配置目录: " + configPath);
TOMCAT_CONFIG_DIR = defaultPath+"\\config";
return TOMCAT_CONFIG_DIR;
}
Log("无法确定Tomcat配置目录");
return null;
}
/**
* 获取所有配置目录,按优先级排序
*/
private List<String> getConfigDirectories() {
List<String> configDirs = new ArrayList<>();
// 1. 从系统属性中获取
String configDirFromProperty = System.getProperty(CONFIG_DIR_PROPERTY);
if (configDirFromProperty != null && !configDirFromProperty.isEmpty()) {
configDirs.add(configDirFromProperty);
Log("从系统属性中获取配置目录: "+ configDirFromProperty);
}
// 2. 从环境变量中获取
String configDirFromEnv = System.getenv(CONFIG_DIR_ENV);
if (configDirFromEnv != null && !configDirFromEnv.isEmpty()
&& !configDirs.contains(configDirFromEnv)) {
configDirs.add(configDirFromEnv);
Log("从环境变量中获取配置目录: "+ configDirFromEnv);
}
// 3. 使用默认配置目录
if (!configDirs.contains(DEFAULT_CONFIG_DIR)) {
configDirs.add(DEFAULT_CONFIG_DIR);
}
// 4. 添加Tomcat配置目录
String tomcatConfigDir = getTomcatConfigDir();
if (tomcatConfigDir != null && !configDirs.contains(tomcatConfigDir)) {
configDirs.add(tomcatConfigDir);
}
// 5. 添加应用程序本地路径
// configDirs.addAll(Arrays.asList(LOCAL_CONFIG_PATHS));
return configDirs;
}
@Override
public int getOrder() {
// 确保在ConfigDataEnvironmentPostProcessor之前运行
return ConfigDataEnvironmentPostProcessor.ORDER - 1;
}
private void Log(String msg){
log.info(msg);
System.out.println(msg);
}
}
\ No newline at end of file
......@@ -74,6 +74,17 @@ public class DataInitManager {
public void DataInit() {
try {
log.info("smfcore Version:["+version+"], 初始化环境...");
boolean found = Boolean.parseBoolean(
System.getProperty("smfcore.external.config.found", "false"));
String externalConfigPath = System.getProperty("smfcore.external.config.path");
if (found) {
log.info("使用外部配置文件: " + externalConfigPath);
} else {
log.info("未找到外部配置文件,使用内部配置文件");
}
startRunTime=new Date();
//查询admin的用户是否存在
String userName = Constants.SUPER_USERNAME;
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!