Issue
@Component
public class AwsS3Client {
private AmazonS3 amazonS3;
public AmazonS3 getAmazonS3() {
return this.amazonS3;
}
}
......
@Autowired
private AwsS3Client awsS3Client;
if (Objects.isNull(awsS3Client.getAmazonS3())) {
awsS3Client.createSessionWithAssumeRoleCredentials();
}
But for this code awsS3Client.getAmazonS3()
I get:
Required type: Object
Provided: AmazonS3
AmazonS3 is located into another utility jar file. Do you know how I can fix this? I use aws sdk Version 1.11.971
Solution
Not sure what you are trying to do here. Here is a sample of how to create an S3Client
AWSCredentials credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
Assuming you need a createSessionWithAssumeRoleCredentials on AwsS3Client, Wouldn't it make more sense to have an S3ClientFactory which has a static method createSessionWithAssumeRoleCredentials which creates an S3 client for the set of credential that you pass? Credentials are required to instantiate an S3 client, so have a createSessionWithAssumeRoleCredentials method on an S3Client instance makes little sense.
If you are sure that you just need to use the S3 client with just one set of credential, then shouldn't you do something like this?
@Component
public class AwsS3Client {
private S3Client amazonS3;
public AwsS3Client(CustomAWSParameters customAWSParameters){
return createAwsS3ClientWithCredentials(customAWSParameters.getAccessKey, customAWSParameters.getSecretKey, customAWSParameters.getAwsProperties)
}
private static AmazonS3 createAwsS3ClientWithCredentials(String accessKey, String secretKey, AwsProperties awsProperties){
AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey);
awsCredentialsProvider = StaticCredentialsProvider.create(awsBasicCredentials);
amazonS3 = S3Client.builder()
.region(Region.of(awsS3Properties.getRegion()))
.credentialsProvider(awsCredentialsProvider)
.build();
}
}
You can have type safety checks, and other exception handling after/during creating the S3Client instance.
Answered By - Nilay Shah
Answer Checked By - David Marino (JavaFixing Volunteer)