SpringBoot配置文件内容读取

文章目录

前言

一、使用@Value注解

二、外部配置文件读取

三、原始方式


前言

以文件上传为例,上传的路径等信息不能硬编码,配置在配置文件中是最好的选择。


一、使用@Value注解

在application.yml(application.properties)中配置阿里云oos文件上传参数

在Controller中使用@Value注解注入

二、外部配置文件读取

创建一个配置类。

@Component
@ConfigurationProperties("aliyun.oss.file")
@PropertySource("classpath:student.properties")
@Data
public class UploadProperties {

    private String endpoint;

    private String keyid;

    private String keysecret;

    private String bucketname;
}

在Controller中注入UploadProperties对象

测试获取配置信息

三、原始方式

创建工具类,读取配置文件,然后封装获取参数的方法

public class PropertiesUtil {

    public static String endpoint;
    public static String keyid;
    public static String keysecret;
    public static String bucketname;

    private static Properties properties = new Properties();

    static{
        try {
            properties.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream("oos.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        endpoint =properties.getProperty("aliyun.oss.file.endpoint");
        keyid =properties.getProperty("aliyun.oss.file.keyid");
        keysecret =properties.getProperty("aliyun.oss.file.keysecret");
        bucketname =properties.getProperty("aliyun.oss.file.bucketname");
    }

    public static String getProperty(String key){
        String property = properties.getProperty(key);
        if(StringUtils.isNotBlank(property)){
            return property;
        }
        return null;
    }

    public static String getProperty(String key, String defaultValue){
        String property = properties.getProperty(key);
        if(StringUtils.isBlank(property)){
            property = defaultValue;
        }
        return property;
    }
}

 

猜你喜欢

转载自blog.csdn.net/zh137289/article/details/108422537