SpringBoot中application.yml值注入为空问题
项目场景:项目场景:在上传文件至腾讯云OSS时,为了维护方便,在application中建立了tencent云存储相关信息,如下图示:![在这里插入图片描述](https://img-blog.csdnimg.cn/20210401135621225.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_
·
项目场景:
项目场景:在上传文件至腾讯云OSS时,为了维护方便,在application中建立了tencent云存储相关信息,如下:tencent:
appId: xxx
secretId: xxx
secretKey: xxx
region: xxx
photoBucket: xxx
然后在工具类CosUtil中加上注解@Component,并且在相关参数上加入@Value注解注入值,如下:
@Component
public class CosUtil {
@Value("${tencent.appId}")
private static String appId;
@Value("${tencent.secretId}")
private static String secretId;
@Value("${tencent.secretKey}")
private static String secretKey;
@Value("${tencent.region}")
private static String region;
@Value("${tencent.photoBucket}")
private static String photoBucket;
}
在方法中调用参数:
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, KEY, file.getInputStream(),meta);
putObjectRequest.setStorageClass(StorageClass.Standard);
COSClient client = getCosClient();
try {
PutObjectResult putObjectResult = client.putObject(putObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
// 关闭客户端
client.shutdown();
问题描述:
方法接收的参数为空,即secretId、secretKey、bucketName都为空,无法正常地完成业务功能。原因分析:
springBoot高版本无法使用@Value直接注入值解决方案:
在类头加注解@ConfigurationPropertie,并创建set方法,直接在set方法上使用@Value注入配置的值。完美解决问题!@Component
@ConfigurationProperties(prefix = "tencent",ignoreInvalidFields = true,ignoreUnknownFields = true)
public class CosUtil {
private static String appId;
private static String secretId;
private static String secretKey;
private static String region;
private static String photoBucket;
@Value("${tencent.appId}")
public void setAppId(String appId) {
this.appId = appId;
}
@Value("${tencent.secretId}")
public void setSecretId(String secretId) {
this.secretId = secretId;
}
@Value("${tencent.secretKey}")
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
@Value("${tencent.region}")
public void setRegion(String region) {
this.region = region;
}
@Value("${tencent.photoBucket}")
public void setPhotoBucket(String photoBucket) {
this.photoBucket = photoBucket;
}
..............
更多推荐
已为社区贡献2条内容
所有评论(0)