这里写自定义目录标题
JAVA获取配置文件
大部分Java应用程序可以使用依赖注入的方式再通过@Value获取配置文件中的值,但是有些功能没办法进行依赖注入
不用依赖注入获取配置文件
导入maven配置文件,该工具可以更好的获取配置文件
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.2.0</version>
</dependency>
工具代码类
package com.clear.zhfw.bus.utils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigParseOptions;
import com.typesafe.config.ConfigSyntax;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
/**
* @author 嘟嘟嘟
* @date 2023年04月17日
**/
@Slf4j
public class AppConfigUtil {
// 获取jar包运行时指定配置文件路径的地址,即-Dspring.config.location地址
// java jar -Dspring.config.location=D:\test\config\ "test.jar"
private static final String CONFIG_FILE = System.getProperty("spring.config.location");
private static final Config config = loadConfig();
private AppConfigUtil() {
}
private static Config loadConfig() {
log.info("加载到的配置文件路径为:{}", CONFIG_FILE);
if (CONFIG_FILE != null) {
Config config = getConfigByFile(CONFIG_FILE + "application.properties");
String active = config.getString("spring.profiles.active");
Config activeConfig = getConfigByFile(CONFIG_FILE + "application-" + active + ".properties");
config = config.withFallback(activeConfig);
return config;
} else {
Config config = getConfigByActive("application.properties");
String active = config.getString("spring.profiles.active");
Config activeConfig = getConfigByActive("application-" + active + ".properties");
config = config.withFallback(activeConfig);
return config;
}
}
public static String getProperty(String key) {
return config.getString(key);
}
private static Config getConfigByActive(String pre) {
return ConfigFactory.parseResources(pre, ConfigParseOptions.defaults().setSyntax(ConfigSyntax.PROPERTIES));
}
private static Config getConfigByFile(String fileUrl) {
return ConfigFactory.parseFile(new File(fileUrl));
}
}