引言
SpringBoot中可以使用@Value
直接resources目录下的配置文件中读取相关配置参数。但是非微服务模式下,可以使用类加载机制进行获取。
模板
public class PropertiesConfig {
private static Properties properties;
private PropertiesConfig() {}
public static Properties getInstance() throws Exception{
synchronized(Properties.class) {
if (properties == null) {
properties = new Properties();
try (InputStream in = PropertiesConfig.class.getClassLoader().getResourceAsStream("application.properties")) {
properties.load(in);
} catch (Exception e) {
logger.error("获取配置文件异常: {}", e.getMessage());
}
}
}
return properties;
}
}