Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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()
The default credentials chain asks six providers in order: system properties, environment variables, web identity token, profile file, container endpoint, instance profile. On a laptop with AWS_PROFILE=relay, the profile answers and the caller is user/relay-dev. In a container with AWS_CONTAINER_CREDENTIALS_FULL_URI set, the container provider answers and the caller is the assumed role relay-app-role, with temporary credentials. 1 systemproperties 2 environmentvariables 3 web identitytoken file 4 profilefile 5 containerendpoint 6 instanceprofile laptop: AWS_PROFILE=relayuser/relay-dev container endpointassumed-role/relay-app-role first one that answers wins
The code is the same in both places. The environment decides the identity.

With DEBUG logging on the chain, you can watch it. Three starts of the same jar:

Started withProvider that answeredTemporaryCaller
AWS_PROFILE=relayProfileCredentialsProvider (profileName=relay)falseuser/relay-dev
AWS_ACCESS_KEY_ID and secret in the environmentEnvironmentVariableCredentialsProviderfalseuser/relay-dev
AWS_CONTAINER_CREDENTIALS_FULL_URIContainerCredentialsProvidertrueassumed-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 happenedWhat the SDK threw
Wrong secret nameResourceNotFoundException: Secrets Manager can't find the specified secret. (Status Code: 400)
Key not in the bucketNoSuchKey: The specified key does not exist. (the app answered 404)
No credentials anywhereSdkClientException: Unable to load credentials from any of the providers in the chain, after 15.1 s
A server that never answersApiCallAttemptTimeoutException: ... 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 toString prints 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Spring Boot · 32 of 99

Previous
A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
Next post
Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire

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.

On this page

  • One BOM, three modules
  • Clients are beans
  • The default chain decides who you are
  • A secret, read once, never logged
  • S3: put, get, delete
  • When it goes wrong
  • Common mistakes
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.