SpringBoot配置文件内容读取

文章目录


前言

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


 

一、使用@Value注解

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

在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;
    }
}

 


 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值