Problem:
Set up a basic Java Spring project for working with DynamoDB.
Solution Summary:
I will be using Spring Boot, however, I won’t be using any Spring Boot specific started dependencies for AWS. There will be a separate note on using spring-cloud-starter-aws starter dependency of Spring Boot.
Prerequisites:
This is the beginning of a new lab. Though having done the previous labs are an advantage, it is not a requirement.
Solution Steps:
Context class
I have created a separate context configuration class for DynamoDB in a package called context under the main class package:
package com.buddytutor.aws.dynamodb.context;
…
@Configuration
public class AWSDynamoDBContext {
…
In case of a non-Spring boot application, this context configuration class needs to be imported to the main Spring config file (@Configuration).
I have added the below dependency to maven file:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.11.98</version>
</dependency>
Note: You may use the latest version available in the maven repository at https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-dynamodb.
I will create two DynamoDB client beans inside AWSDynamoDBContext: one for cloud and one for local. While you have to only specify the region for the cloud, you need to specify the local endpoint for local. I will make the local version as Primary.
// For cloud.
@Bean
public AmazonDynamoDB amazonDynamoDB() {
final AWSCredentials credentials = new BasicAWSCredentials(
awsAccessKeyId,
awsSecretAccessKey);
return AmazonDynamoDBClientBuilder.standard()
.withClientConfiguration(PredefinedClientConfigurations.dynamoDefault())
.withRegion(awsDynamoDBRegion)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
// For Local.
@Primary
@Bean
public AmazonDynamoDB amazonDynamoDBLocal() {
final AWSCredentials credentials = new BasicAWSCredentials(
awsAccessKeyId,
awsSecretAccessKey);
return AmazonDynamoDBClientBuilder.standard()
.withClientConfiguration(PredefinedClientConfigurations.dynamoDefault())
.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
awsDynamoDBEndpoint,
awsDynamoDBRegion))
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
Note: You could also specify endpoint in cloud, but is not recommended as it is already picked up based on the endpoint.
Recent comments