前言

    在项目中经常会用到从配置文件读取配置的需求,毕竟有些例如ip/端口/文件存储路径等配置,为了代码的复用性和可移植性,最好是能从配置文件读,最大程度避免在代码中写死(不要硬编码,不要硬编码)

遇到过好几种从配置文件读取配置的方法,在此做下汇总,方便之后复用~

方法

一、使用Properties配置类对象获取

一般会给一个static静态代码块,在其中实例化好Properties对象,然后定义一个方法,根据key去配置文件中获取对应的配置

其中配置文件可以直接写文件名的原因:通过类加载器进行加载,项目在编译之后application.yml在classes编译代码目录中,所以可以通过类加载器直接找到

    private static Properties properties = new Properties();
 
    static {
        try {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("application.yml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static String getKey(String key) {
        Object o = properties.get(key);
        return o != null ? o +"" : null;
    }
 
    public static void main(String[] args) {
        System.out.println(getKey("imagePath"));
    }

二、使用@Component中的@Value获取

这个方法一般在SpringBoot项目中常用,利用spring特性

@Component
public class FilePathConfig {
 
    @Value(("${imagePath}"))
    private String imagePath;
 
    public String getImagePath() {
        return imagePath;
    }
 
    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }
}

三、使用@ConfigurationProperties(prefix = “前缀”)获取

在类前面加这个注解标明加载配置文件,如果有一系列统一前缀的配置,可通过配置前缀精准匹配减少查询范围

参考:https://blog.csdn.net/weixin_43831204/article/details/105177511

@Component
@ConfigurationProperties()
@Data
public class testProperties {
    private  private String iamgePath;
}
// 获取imagePath
 
 
    @Autowired
    testProperties properties;
 
public String getImagePath() {
    return properties.getImagePath();
 
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐