How to connect AWS using spring boot example code
To connect to AWS using Spring Boot, you can use the AWS SDK for Java.
Here is an example code that shows how to connect to AWS using Spring Boot:
1. Add the AWS SDK dependency to your project. You can do this by adding the following to your pom.xml file:
3. Create an AWS client bean. In your Spring Boot application, create a bean for the AWS client that you want to use.
For example, to create an S3 client, you can use the following code:
2. Configure the AWS credentials. You can either set the credentials as environment variables or use a profile file. Here's an example of setting the credentials as environment variables:<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk</artifactId> <version>1.12.91</version> </dependency>
export AWS_ACCESS_KEY_ID=<your-access-key> export AWS_SECRET_ACCESS_KEY=<your-secret-key> export AWS_REGION=<your-region>
@Configuration public class AwsConfig { @Value("${aws.s3.region}") private String region; @Bean public AmazonS3 amazonS3() { AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain(); return AmazonS3ClientBuilder.standard() .withCredentials(credentialsProvider) .withRegion(region) .build(); } }4. Use the AWS client in your code. You can now use the AWS client that you created in your code to interact with AWS services. Here's an example of using the S3 client to list all the buckets in your account:
@RestController public class MyController { private final AmazonS3 amazonS3; public MyController(AmazonS3 amazonS3) { this.amazonS3 = amazonS3; } @GetMapping("/buckets") public ListThis is just a simple example, but you can use the AWS SDK to interact with a wide variety of AWS services, including EC2, RDS, DynamoDB, and more.listBuckets() { List buckets = amazonS3.listBuckets(); return buckets.stream() .map(Bucket::getName) .collect(Collectors.toList()); } }
Comments
Post a Comment