项目场景:

项目场景:在上传文件至腾讯云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;
    }
    ..............
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐