The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
The same jar starts three times and never sees a key in its code. With a profile it runs as user/relay-dev; with a container endpoint it runs as the assumed role relay-app-role, with temporary credentials. Then S3 put, get and delete, a secret read once with only its key names logged, three failures, and an attempt timeout that fires three times.
What you will learn
- Add only the SDK modules you use, with one BOM for the version
- Build S3, Secrets Manager and STS clients as Spring beans with a region and timeouts
- Let the default credentials chain find a profile on a laptop and a role in a container, with no keys in code
- Read a secret once without logging it, and recognise the SDK's typical errors and timeouts
Before you start
- A Spring Boot REST API
- Private S3 Uploads from FastAPI: A Locked Bucket, a Key per User, and Presigned Links That Expire
Most bugs with AWS from Java aren't in the S3 call. They're in how the client is built: which keys it uses, which region it talks to, and how long it waits. This article builds three clients as Spring beans, starts the same jar in three different environments, and shows which identity the SDK picked each time. There are no access keys anywhere in the code.
Every run here was against LocalStack 4.9, a local stand-in for AWS, so no account was needed. LocalStack accepts any credentials and doesn't check permissions; everything about who the caller is, is real SDK behaviour.
One BOM, three modules
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws-sdk.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The SDK is split into one module per service. The BOM sets one version (2.59.3 here) for all of them, and the project then adds only s3, secretsmanager and sts without versions. STS is there for one call: "who am I?" at startup. There's no Spring Cloud AWS starter, so nothing is configured behind your back.
Clients are beans
@Bean
AwsCredentialsProvider awsCredentials() {
return DefaultCredentialsProvider.builder().build();
}
@Bean
S3Client s3Client(AwsProperties p, AwsCredentialsProvider credentials) {
return newS3(p, credentials);
}
static S3Client newS3(AwsProperties p, AwsCredentialsProvider credentials) {
var b = S3Client.builder().region(Region.of(p.region()))
.credentialsProvider(credentials).overrideConfiguration(timeouts(p));
if (p.hasEndpoint()) {
b.endpointOverride(URI.create(p.endpoint())).forcePathStyle(true);
}
return b.build();
}
static ClientOverrideConfiguration timeouts(AwsProperties p) {
return ClientOverrideConfiguration.builder()
.apiCallAttemptTimeout(p.attemptTimeout())
.apiCallTimeout(p.callTimeout())
.build();
}
Each client gets three things. A region, eu-west-2, from configuration. A credentials provider, the default chain, with no key or profile name in code. And timeouts: one try may take 5 seconds (attempt-timeout), the whole call, retries included, 15 seconds (call-timeout). The endpoint override is only for the local stand-in; on AWS the property is empty and the SDK uses the real endpoint. The Secrets Manager and STS clients are built the same way.
A client holds a connection pool and threads. Build it once, as a bean, and share it. In this run, 20 uploads through one shared client took 193 ms, and through a new client each time 1026 ms. Those are times against a local store and change every run, but the gap is the point.
The default chain decides who you are
DefaultCredentialsProvider asks a list of providers in order and uses the first one that answers. The SDK printed its own order when nothing answered:
SystemPropertyCredentialsProvider(), EnvironmentVariableCredentialsProvider(),
WebIdentityTokenFileCredentialsProvider(), ProfileCredentialsProvider(profileName=default),
ContainerCredentialsProvider(), InstanceProfileCredentialsProvider()
With DEBUG logging on the chain, you can watch it. Three starts of the same jar:
| Started with | Provider that answered | Temporary | Caller |
|---|---|---|---|
AWS_PROFILE=relay | ProfileCredentialsProvider (profileName=relay) | false | user/relay-dev |
AWS_ACCESS_KEY_ID and secret in the environment | EnvironmentVariableCredentialsProvider | false | user/relay-dev |
AWS_CONTAINER_CREDENTIALS_FULL_URI | ContainerCredentialsProvider | true | assumed-role/relay-app-role/relay-task |
The first line is a developer's laptop. The third is how a task on ECS gets credentials: ECS sets that variable, and the SDK fetches short-lived credentials for the task's role. (Here a small local server played the ECS endpoint.) No keys live in the image, and they expire on their own. The startup report shows both facts:
var identity = credentials.resolveIdentity().join();
log.info("Credentials resolved, temporary: {}", identity.expirationTime().isPresent());
log.info("Caller {}", sts.getCallerIdentity().arn());
A secret, read once, never logged
void load() {
String json = secrets.getSecretValue(r -> r.secretId(props.mailSecret())).secretString();
@SuppressWarnings("unchecked")
Map<String, String> parsed = JsonMapper.builder().build().readValue(json, Map.class);
values = Map.copyOf(parsed);
log.info("Secret {} loaded, keys {}", props.mailSecret(), new TreeSet<>(values.keySet()));
}
@Override
public String toString() {
return "MailSecret[username=" + username() + ", password=********]";
}
The mail credentials live in Secrets Manager as relay/mail. The class reads them once at startup and keeps them in memory. The log line names only the keys: Secret relay/mail loaded, keys [password, username]. And toString masks the password, so an accidental log.info("{}", secret) can't leak it.
S3: put, get, delete
public void put(String key, byte[] bytes, String contentType) {
s3.putObject(r -> r.bucket(props.bucket()).key(key).contentType(contentType), RequestBody.fromBytes(bytes));
}
public byte[] get(String key) {
return s3.getObjectAsBytes(r -> r.bucket(props.bucket()).key(key)).asByteArray();
}
public void delete(String key) {
s3.deleteObject(r -> r.bucket(props.bucket()).key(key));
}
Uploading a 2048-byte PNG answered tickets/42/printer-error.png stored, 2048 bytes. Downloading it gave 200 2048 bytes, byte for byte the same file. After the delete, the listing was empty. For browser uploads you'd rather hand out pre-signed URLs, so the file doesn't pass through the app at all.
When it goes wrong
| What happened | What the SDK threw |
|---|---|
| Wrong secret name | ResourceNotFoundException: Secrets Manager can't find the specified secret. (Status Code: 400) |
| Key not in the bucket | NoSuchKey: The specified key does not exist. (the app answered 404) |
| No credentials anywhere | SdkClientException: Unable to load credentials from any of the providers in the chain, after 15.1 s |
| A server that never answers | ApiCallAttemptTimeoutException: ... 1000 millis (SDK Attempt Count: 3) |
The last one is worth reading closely. With the attempt timeout set to one second, each try was cut off after 1000 ms, and the SDK retried until it had made 3 attempts. That's the attempt timeout firing, not the call timeout. Without either, a call to a stuck endpoint can hold a request thread for a very long time.
On real AWS there's one more you'll meet: AccessDenied, when the identity the chain found has no permission for the call. LocalStack doesn't check permissions, so it isn't shown here. The fix is in IAM, not in the code: give the role exactly the actions this class uses.
Common mistakes
- Access keys in
application.yaml. They end up in git and in images. Let the chain find a profile or a role. - A new client per request. Slow, and it leaks connections. One bean, shared.
- No region set. The SDK then guesses from the environment, and a laptop and a container may guess differently.
- No timeouts. A stuck endpoint holds threads until something else gives up.
- Logging a secret's value, or an object whose
toStringprints it.
Try it yourself
Start the jar with both AWS_PROFILE=relay and the two key environment variables set. Which provider answers, and why? Check the DEBUG lines of the chain to confirm.
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
