如何使用@value访问spring中的.properties文件?

jfewjypa  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(393)

我想从我的朋友那里得到一些信息 config.properties 包含所有凭据信息的文件,如下所示:

cloud.aws.credentials.accessKey=Hello
cloud.aws.credentials.secretKey=Hellobebe
cloud.aws.s3.bucket=hellome
could.aws.region.static=ap-northeast-2
cloud.stack.auto=false

在java文件中,我尝试使用@value来访问它,但是我无法获得值。下面是我的s3service.java代码

package com.aplusinternational.goTrip.service;

import java.io.IOException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;

import lombok.NoArgsConstructor;

@Service
@NoArgsConstructor
public class S3Service {
    private AmazonS3 s3Client;

    @Value("${cloud.aws.credentials.accessKey}")
    private String accessKey;

    @Value("${cloud.aws.credentials.secretKey}")
    private String secretKey;

    @Value("${cloud.aws.s3.bucket}")
    private String bucket;

    @Value("${cloud.aws.region.static}")
    private String region;

    @PostConstruct
    public void setS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(this.region)
                .build();
    }

    public String upload(MultipartFile multipartFile, String dirName) throws IOException {
        String fileName = dirName + "/" + multipartFile.getOriginalFilename();
        String uploadImageUrl = putS3(multipartFile, fileName);
        //removeNewFile(multipartFile);
        return uploadImageUrl;
    }

    private String putS3(MultipartFile multipartFile, String fileName) throws IOException {
        System.out.println("file is in!: "+ fileName+" putS3");
        System.out.println(this.bucket);
        s3Client.putObject(new PutObjectRequest(bucket, fileName, multipartFile.getInputStream(), null).withCannedAcl(CannedAccessControlList.PublicRead));
        return s3Client.getUrl(bucket, fileName).toString();
    }

}

当我运行它时,它会给我 ${cloud.aws.s3.bucket} 它自己。错误是:在此处输入图像描述
我为此花了几千个小时。请帮帮我!
另外,我可以从同一个.properties文件中获取数据库信息。

r7knjye2

r7knjye21#

@propertysource(值={“classpath:config.properties“,},encoding=”utf-8“)尝试添加此注解。

相关问题