我們有 Spring Boot 2 應用程式,并且有這樣一個任務 - 我們之前保存了 AWS S3 連接詳細資訊(存盤桶、路徑、訪問、秘密),我們需要在運行中創建 AWS S3 客戶端,只是為了測驗與給定細節的聯系。
我想@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)需要那個bean,但是如何動態設定這些連接細節?
也許有更好的方法,任何意見/解決方案表示贊賞,謝謝!
uj5u.com熱心網友回復:
我們可以通過傳遞 AccessKeyId、SecretAccessKey 和 Region 來動態創建 AWS S3 客戶端。這是解決方案。
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.315</version>
</dependency>
@Service
public class AwsS3ClientBuilderService {
public AmazonS3 createAwsS3Client(String accessKeyId, String secretAccessKey, String region){
final BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);
return AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
.withRegion(region)
.build();
}
}
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final AwsS3ClientBuilderService awsS3ClientBuilderService;
@Autowired
public DemoApplication(AwsS3ClientBuilderService awsS3ClientBuilderService) {
this.awsS3ClientBuilderService = awsS3ClientBuilderService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class);
}
@Override
public void run(String... args) throws Exception {
final AmazonS3 amazonS3 = awsS3ClientBuilderService
.createAwsS3Client("accessKeyId","secretAccessKey","eu-west-1");
GetObjectRequest getObjectRequest = new GetObjectRequest("bucketName","keyName");
final S3Object s3Object = amazonS3.getObject(getObjectRequest);
final S3ObjectInputStream objectContent = s3Object.getObjectContent();
//....
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/517184.html
