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 @ 2022-04-11 20:04  Andya_net  阅读(13)  评论(0编辑  收藏  举报  来源