How to Build a Spring Boot OSS Starter Compatible with Amazon S3

This guide walks through creating a reusable Spring Boot starter that abstracts object storage services (OSS) via the Amazon S3 API, covering project setup, Maven dependencies, configuration properties, template interfaces, implementation, auto‑configuration, packaging, and a simple test case.

macrozheng
macrozheng
macrozheng
How to Build a Spring Boot OSS Starter Compatible with Amazon S3

Overview

Object Storage Service (OSS) provides HTTP APIs for storing and retrieving objects such as files, images, and audio. Most commercial OSS providers (Alibaba Cloud OSS, Tencent COS, MinIO, etc.) implement the Amazon S3 protocol, so a Spring Boot starter that uses S3 can work with any of them without code changes.

Project Setup

Create a Maven module named oss-spring-boot-starter. Delete the default Spring Boot application class and the generated test package so that the module only contains the starter code.

Dependencies

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-s3</artifactId>
  <version>1.12.423</version>
</dependency>

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-core</artifactId>
  <version>5.8.5</version>
</dependency>

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>RELEASE</version>
  <scope>compile</scope>
</dependency>

Configuration Properties

Define a POJO OssProperties annotated with @ConfigurationProperties(prefix="oss"). The following properties are bound from application.yml or application.properties:

oss.endpoint=YOUR_ENDPOINT
oss.accessKey=YOUR_ACCESS_KEY
oss.secretKey=YOUR_SECRET_KEY
oss.region=YOUR_REGION
oss.pathStyleAccess=true
oss.maxConnections=100

OSS Template Interface

Create an interface OssTemplate that abstracts common OSS operations:

void createBucket(String bucketName);
List<Bucket> getAllBuckets();
void removeBucket(String bucketName);
void putObject(String bucketName, String objectName, InputStream stream, String contentType) throws Exception;
void putObject(String bucketName, String objectName, InputStream stream) throws Exception;
S3Object getObject(String bucketName, String objectName);
String getObjectURL(String bucketName, String objectName, Integer expires);
void removeObject(String bucketName, String objectName) throws Exception;
List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive);

Implementation

Implement OssTemplateImpl. The class uses Lombok @RequiredArgsConstructor to inject a final AmazonS3 client and annotates methods with @SneakyThrows to simplify exception handling. Example snippets:

@Override
@SneakyThrows
public void createBucket(String bucketName) {
    if (!amazonS3.doesBucketExistV2(bucketName)) {
        amazonS3.createBucket(bucketName);
    }
}

@Override
@SneakyThrows
public List<Bucket> getAllBuckets() {
    return amazonS3.listBuckets();
}

@Override
@SneakyThrows
public void putObject(String bucketName, String objectName, InputStream stream, String contentType) {
    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentType(contentType);
    amazonS3.putObject(bucketName, objectName, stream, meta);
}

@Override
@SneakyThrows
public String getObjectURL(String bucketName, String objectName, Integer expires) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, expires);
    URL url = amazonS3.generatePresignedUrl(bucketName, objectName, cal.getTime());
    return url.toString();
}

Auto‑Configuration

Create OssAutoConfiguration annotated with @Configuration and @EnableConfigurationProperties(OssProperties.class). It declares two beans: AmazonS3 ossClient(OssProperties props) – builds the client using endpoint, region, credentials, max connections, and the pathStyleAccess flag. OssTemplate ossTemplate(AmazonS3 amazonS3) – returns a new OssTemplateImpl when an AmazonS3 bean is present.

@Bean
@ConditionalOnMissingBean
public AmazonS3 ossClient(OssProperties props) {
    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setMaxConnections(props.getMaxConnections());
    AwsClientBuilder.EndpointConfiguration endpointConfig =
        new AwsClientBuilder.EndpointConfiguration(props.getEndpoint(), props.getRegion());
    AWSCredentials credentials = new BasicAWSCredentials(props.getAccessKey(), props.getSecretKey());
    AWSCredentialsProvider provider = new AWSStaticCredentialsProvider(credentials);
    return AmazonS3Client.builder()
        .withEndpointConfiguration(endpointConfig)
        .withClientConfiguration(clientConfig)
        .withCredentials(provider)
        .disableChunkedEncoding()
        .withPathStyleAccessEnabled(props.getPathStyleAccess())
        .build();
}

@Bean
@ConditionalOnBean(AmazonS3.class)
public OssTemplate ossTemplate(AmazonS3 amazonS3) {
    return new OssTemplateImpl(amazonS3);
}

Spring.factories Registration

Add a file META-INF/spring.factories with the following entry so that Spring Boot discovers the auto‑configuration:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.qing.oss.OssAutoConfiguration

Packaging

Remove the default spring-boot-maven-plugin from the starter’s pom.xml to avoid executable‑jar packaging. Then run: mvn clean install The starter JAR is installed into the local Maven repository and can be referenced by other projects.

Usage Example

In a consumer Spring Boot application, add the starter as a dependency and configure the oss.* properties (the example below uses MinIO). Autowire OssTemplate and call its methods:

# application.yml
oss:
  endpoint: http://localhost:9000
  accessKey: minioadmin
  secretKey: minioadmin
  region: us-east-1
  pathStyleAccess: true
  maxConnections: 100
@SpringBootTest
class OssStarterTest {
    @Autowired
    private OssTemplate ossTemplate;

    @Test
    void testCreateBucket() {
        ossTemplate.createBucket("oss02");
    }
}

Running the test creates the bucket oss02 in the configured object‑storage service.

Source Repository

Complete source code for the starter is hosted at:

https://github.com/hujiaqing789/test-spring-boot-starter

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cloud storageOSSspring-bootAmazon S3Starter
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.