Spring—使用类加载从配置文件中读取配置

引言

  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;
    }
}
posted @   Andya_net  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示