0
# Client Builders & Configuration
1
2
The AWS Java SDK Core provides flexible client builder patterns for constructing AWS service clients with custom configurations, credential providers, and advanced options.
3
4
## Core Builder Interfaces
5
6
### Base Client Builder
7
8
```java { .api }
9
// Base builder interface for all AWS clients
10
interface AwsClientBuilder<Subclass extends AwsClientBuilder, TypeToBuild> {
11
Subclass withCredentials(AWSCredentialsProvider credentialsProvider);
12
Subclass withRegion(Regions region);
13
Subclass withRegion(String region);
14
Subclass withEndpointConfiguration(EndpointConfiguration endpointConfiguration);
15
Subclass withClientConfiguration(ClientConfiguration clientConfiguration);
16
Subclass withMetricsCollector(RequestMetricCollector metricsCollector);
17
18
TypeToBuild build();
19
}
20
21
// Synchronous client builder
22
interface AwsSyncClientBuilder<Subclass extends AwsSyncClientBuilder, TypeToBuild>
23
extends AwsClientBuilder<Subclass, TypeToBuild> {
24
// Synchronous-specific builder methods
25
}
26
27
// Asynchronous client builder
28
interface AwsAsyncClientBuilder<Subclass extends AwsAsyncClientBuilder, TypeToBuild>
29
extends AwsClientBuilder<Subclass, TypeToBuild> {
30
Subclass withExecutorFactory(ExecutorFactory executorFactory);
31
// Asynchronous-specific builder methods
32
}
33
```
34
35
### Endpoint Configuration
36
37
```java { .api }
38
// Endpoint configuration for custom endpoints
39
class EndpointConfiguration {
40
public EndpointConfiguration(String endpoint, String signingRegion);
41
public String getEndpoint();
42
public String getSigningRegion();
43
}
44
```
45
46
## Client Configuration Factory
47
48
### Configuration Factory
49
50
```java { .api }
51
// Factory for creating client configurations
52
class ClientConfigurationFactory {
53
public ClientConfiguration getConfig();
54
protected ClientConfiguration getDefaultConfig();
55
56
// Configuration with advanced options
57
public ClientConfiguration getConfigWithRequestTimeout(int requestTimeout);
58
public ClientConfiguration getConfigWithClientExecutionTimeout(int clientExecutionTimeout);
59
}
60
```
61
62
### Predefined Configurations
63
64
```java { .api }
65
// Predefined client configurations for common scenarios
66
class PredefinedClientConfigurations {
67
// Configuration for default retry policy
68
public static ClientConfiguration defaultConfig();
69
70
// Configuration optimized for high throughput
71
public static ClientConfiguration highThroughputConfig();
72
73
// Configuration optimized for low latency
74
public static ClientConfiguration lowLatencyConfig();
75
76
// Configuration for mobile environments
77
public static ClientConfiguration mobileConfig();
78
79
// Configuration with no retry policy
80
public static ClientConfiguration noRetryConfig();
81
}
82
```
83
84
## Advanced Configuration Options
85
86
### Advanced Config
87
88
```java { .api }
89
// Advanced configuration options
90
class AdvancedConfig {
91
public static final AdvancedConfig EMPTY;
92
93
public static Builder builder();
94
95
interface Builder {
96
Builder putAdvancedOption(AdvancedConfigOptionKey<T> option, T value);
97
AdvancedConfig build();
98
}
99
100
public <T> Optional<T> getAdvancedOption(AdvancedConfigurationKey<T> key);
101
}
102
103
// Advanced configuration option keys
104
class AdvancedConfigOptionKey<T> {
105
public static final AdvancedConfigOptionKey<Boolean> ENABLE_DEFAULT_METRICS;
106
public static final AdvancedConfigOptionKey<Boolean> USE_LEGACY_USER_AGENT;
107
public static final AdvancedConfigOptionKey<Boolean> DISABLE_HOST_PREFIX_INJECTION;
108
}
109
```
110
111
### Executor Factory
112
113
```java { .api }
114
// Factory for creating custom executors for async clients
115
interface ExecutorFactory {
116
Executor newExecutor();
117
}
118
119
// Cached thread pool executor factory
120
class CachedThreadPoolExecutorFactory implements ExecutorFactory {
121
public CachedThreadPoolExecutorFactory();
122
public Executor newExecutor();
123
}
124
125
// Fixed thread pool executor factory
126
class FixedThreadPoolExecutorFactory implements ExecutorFactory {
127
public FixedThreadPoolExecutorFactory(int threadPoolSize);
128
public Executor newExecutor();
129
}
130
```
131
132
## Basic Usage Examples
133
134
### Simple Client Construction
135
136
```java
137
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
138
import com.amazonaws.regions.Regions;
139
import com.amazonaws.services.s3.AmazonS3;
140
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
141
142
// Simple S3 client with default configuration
143
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
144
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
145
.withRegion(Regions.US_EAST_1)
146
.build();
147
```
148
149
### Custom Client Configuration
150
151
```java
152
import com.amazonaws.ClientConfiguration;
153
import com.amazonaws.retry.PredefinedRetryPolicies;
154
import com.amazonaws.services.dynamodb.AmazonDynamoDB;
155
import com.amazonaws.services.dynamodb.AmazonDynamoDBClientBuilder;
156
157
// DynamoDB client with custom configuration
158
ClientConfiguration config = new ClientConfiguration()
159
.withMaxConnections(50)
160
.withConnectionTimeout(10000)
161
.withSocketTimeout(30000)
162
.withRetryPolicy(PredefinedRetryPolicies.DYNAMODB_DEFAULT);
163
164
AmazonDynamoDB dynamoClient = AmazonDynamoDBClientBuilder.standard()
165
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
166
.withRegion(Regions.US_WEST_2)
167
.withClientConfiguration(config)
168
.build();
169
```
170
171
### Custom Endpoint Configuration
172
173
```java
174
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
175
import com.amazonaws.services.s3.AmazonS3;
176
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
177
178
// S3 client with custom endpoint (e.g., for localstack)
179
EndpointConfiguration endpointConfig = new EndpointConfiguration(
180
"http://localhost:4566", // Custom endpoint URL
181
"us-east-1" // Signing region
182
);
183
184
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
185
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
186
.withEndpointConfiguration(endpointConfig)
187
.withPathStyleAccessEnabled(true)
188
.build();
189
```
190
191
### Asynchronous Client Construction
192
193
```java
194
import com.amazonaws.client.builder.ExecutorFactory;
195
import com.amazonaws.services.s3.AmazonS3Async;
196
import com.amazonaws.services.s3.AmazonS3AsyncClientBuilder;
197
import java.util.concurrent.Executors;
198
199
// Custom executor factory for async operations
200
ExecutorFactory executorFactory = () -> Executors.newFixedThreadPool(10);
201
202
// Asynchronous S3 client
203
AmazonS3Async s3AsyncClient = AmazonS3AsyncClientBuilder.standard()
204
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
205
.withRegion(Regions.US_EAST_1)
206
.withExecutorFactory(executorFactory)
207
.build();
208
```
209
210
### Predefined Configurations
211
212
```java
213
import com.amazonaws.ClientConfigurationFactory;
214
import com.amazonaws.PredefinedClientConfigurations;
215
216
// Using predefined configurations
217
ClientConfiguration highThroughputConfig =
218
PredefinedClientConfigurations.highThroughputConfig();
219
220
ClientConfiguration mobileConfig =
221
PredefinedClientConfigurations.mobileConfig();
222
223
// Using configuration factory
224
ClientConfigurationFactory configFactory = new ClientConfigurationFactory();
225
ClientConfiguration factoryConfig = configFactory.getConfig();
226
```
227
228
## Advanced Configuration Patterns
229
230
### Multiple Region Clients
231
232
```java
233
import java.util.HashMap;
234
import java.util.Map;
235
236
// Creating clients for multiple regions
237
Map<Regions, AmazonS3> s3Clients = new HashMap<>();
238
239
for (Regions region : Arrays.asList(Regions.US_EAST_1, Regions.EU_WEST_1, Regions.AP_SOUTHEAST_1)) {
240
AmazonS3 client = AmazonS3ClientBuilder.standard()
241
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
242
.withRegion(region)
243
.build();
244
s3Clients.put(region, client);
245
}
246
```
247
248
### Configuration with Custom Metrics
249
250
```java
251
import com.amazonaws.metrics.RequestMetricCollector;
252
253
// Custom metrics collector
254
RequestMetricCollector metricsCollector = new RequestMetricCollector() {
255
@Override
256
public void collectMetrics(Request<?> request, Response<?> response) {
257
// Custom metrics collection logic
258
System.out.println("Request completed: " + request.getServiceName());
259
}
260
};
261
262
// Client with custom metrics
263
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
264
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
265
.withRegion(Regions.US_EAST_1)
266
.withMetricsCollector(metricsCollector)
267
.build();
268
```
269
270
## Best Practices
271
272
### Resource Management
273
274
```java
275
// Always close clients when done
276
try (AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
277
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
278
.withRegion(Regions.US_EAST_1)
279
.build()) {
280
281
// Use the client
282
s3Client.listBuckets();
283
284
} // Client automatically closed
285
```
286
287
### Error Handling in Builder Pattern
288
289
```java
290
try {
291
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
292
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
293
.withRegion(Regions.US_EAST_1)
294
.build();
295
296
} catch (SdkClientException e) {
297
// Handle client configuration errors
298
System.err.println("Failed to create S3 client: " + e.getMessage());
299
}
300
```
301
302
### Thread Safety Considerations
303
304
```java
305
// Clients are thread-safe and can be shared
306
private static final AmazonS3 S3_CLIENT = AmazonS3ClientBuilder.standard()
307
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
308
.withRegion(Regions.US_EAST_1)
309
.build();
310
311
// Safe to use from multiple threads
312
public void uploadFile(String key, File file) {
313
S3_CLIENT.putObject("my-bucket", key, file);
314
}
315
```
316
317
## Migration from Legacy Constructor Pattern
318
319
### Before (Legacy Pattern)
320
321
```java
322
// Old constructor-based approach (deprecated)
323
AmazonS3 s3Client = new AmazonS3Client(
324
DefaultAWSCredentialsProviderChain.getInstance(),
325
clientConfiguration
326
);
327
s3Client.setRegion(Region.getRegion(Regions.US_EAST_1));
328
```
329
330
### After (Builder Pattern)
331
332
```java
333
// New builder-based approach (recommended)
334
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
335
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
336
.withClientConfiguration(clientConfiguration)
337
.withRegion(Regions.US_EAST_1)
338
.build();
339
```
340
341
The builder pattern provides better fluent API design, compile-time safety, and easier configuration management compared to the legacy constructor approach.