文章目录
前言
以文件上传为例,上传的路径等信息不能硬编码,配置在配置文件中是最好的选择。
一、使用@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;
}
}