Skip to content
javahacks.dev
Spring Boot

How to Write Your Own Spring Boot Starter Step by Step

Write a Spring Boot starter in two modules: an auto configuration with properties and conditions, and a thin starter that pulls it in with its dependencies.

5 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Spring Security, Apache Maven, Gradle and Spring logos.

A starter is worth writing when several services need the same client, filter or defaults, and you want each of them to get it from one dependency and one property. The pattern is two modules and a registration file, and the part that decides whether the result is pleasant to use is how it backs off when an application wants something different. This guide builds a small greeting starter on Spring Boot 4, tests it without a running application and lists what to keep out of a shared starter. The same structure holds for a database client, a metrics bundle or an internal security filter.

Module 1: the autoconfigure module

This module holds the code and the configuration classes. Start with the properties, then the class being offered, then the auto-configuration that wires them together.

java
@ConfigurationProperties("greeting")
public record GreetingProperties(String prefix) {

    public GreetingProperties {
        if (prefix == null) {
            prefix = "Hello";
        }
    }
}
java
public class Greeter {

    private final String prefix;

    public Greeter(String prefix) { this.prefix = prefix; }

    public String greet(String name) { return prefix + ", " + name; }
}
java
@AutoConfiguration
@ConditionalOnClass(Greeter.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    Greeter greeter(GreetingProperties properties) {
        return new Greeter(properties.prefix());
    }
}

The compact constructor of the record supplies the default, so the starter works with no configuration at all. @ConditionalOnMissingBean is the line that makes the starter polite: if the application defines its own Greeter, yours steps aside instead of causing a duplicate-bean failure. @ConditionalOnClass guards against the optional-dependency case, where the class may not be on the classpath. The way these conditions are evaluated is described in how auto-configuration works.

Register it

Spring Boot finds auto-configurations through an imports file, one class name per line.

src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsText
dev.javahacks.greeting.GreetingAutoConfiguration

Without this file nothing is auto-configured, and the failure is silent: the application starts and the bean is not there. Component scanning does not rescue you, because the starter's package is not under the application's root package, a point explained in project structure. Older tutorials register the class in spring.factories, which Spring Boot no longer reads for this purpose. If a user reports that the starter does nothing, check this file's path and spelling first.

Make the properties discoverable

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

The processor generates META-INF/spring-configuration-metadata.json at build time, so an IDE completes greeting.prefix, shows the Javadoc and warns about unknown keys. Document each property with a Javadoc comment on the record component. That metadata file is the starter's user interface, and for most users it replaces the README.

Module 2: the starter

The starter module has no code. Its pom.xml depends on the autoconfigure module and on anything the user needs at runtime.

XML
<artifactId>greeting-spring-boot-starter</artifactId>
<dependencies>
  <dependency>
    <groupId>dev.javahacks</groupId>
    <artifactId>greeting-spring-boot-autoconfigure</artifactId>
    <version>${project.version}</version>
  </dependency>
</dependencies>

The split exists so a user can depend on the starter for the convenience, while another library can depend only on the autoconfigure module and bring its own dependencies. For a small internal starter, one module is acceptable; split when a second consumer appears. Naming matters: acme-spring-boot-starter is the convention for third parties, and names beginning with spring-boot-starter- belong to the Spring Boot project itself.

What the user gets

An application that adds greeting-spring-boot-starter can inject Greeter with no configuration, set greeting.prefix in its properties, or define its own Greeter bean to replace the default. That is the whole contract of a starter: sensible defaults that back off. Keep the surface small and document every property. Do not start threads, open connections or call remote services from a bean method without a switch to turn that off, because a user who adds the dependency to run a test should not find sockets opening in the background.

Test it without an application

java
class GreetingAutoConfigurationTest {

    private final ApplicationContextRunner runner = new ApplicationContextRunner()
            .withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));

    @Test
    void usesPrefixProperty() {
        runner.withPropertyValues("greeting.prefix=Hi")
              .run(ctx -> assertThat(ctx.getBean(Greeter.class).greet("Ada")).isEqualTo("Hi, Ada"));
    }

    @Test
    void backsOffForUserBean() {
        runner.withBean(Greeter.class, () -> new Greeter("Yo"))
              .run(ctx -> assertThat(ctx).hasSingleBean(Greeter.class));
    }
}

ApplicationContextRunner starts a context in milliseconds and makes conditions testable: one test per property, one for the back-off, one for the missing-class case with FilteredClassLoader. These tests are the only way to be sure a change to a condition does not break users silently. The JUnit mechanics are in the JUnit 5 tutorial.

What to keep out of a starter

Do not put application policy in a shared starter: retries, timeouts and error handling that one team chose become everyone's behaviour. Do not force a transitive dependency version that conflicts with the application's, since the application's BOM should win. Avoid @ComponentScan inside auto-configuration, because it pulls in whatever it finds. And do not read environment variables directly; bind everything through @ConfigurationProperties, so it can be set in any of the places Spring Boot supports.

Versioning and compatibility

A starter is a published API, and its users cannot see your tests. Use semantic versions and treat a renamed property as a breaking change. When you must rename, keep the old key working for a release by declaring it as deprecated with a replacement in additional-spring-configuration-metadata.json, and Spring Boot's spring-boot-properties-migrator will tell users which of their keys moved. State the range of Spring Boot versions you support, and run the autoconfigure tests against the oldest and the newest of them in CI. Auto-configuration classes change between Boot versions, so a starter that was fine on one minor release can fail on the next for a reason unrelated to your code.

Troubleshooting a starter that does nothing

Start the consuming application with --debug and read the conditions report. Your auto-configuration should appear under "Positive matches" or "Negative matches" with the reason. If it is absent from both lists, the imports file was not found: check the path inside the jar with jar tf, and make sure the resources directory is packaged. If it appears as negative because of @ConditionalOnMissingBean, the application defines a bean of that type, perhaps through a component scan that picked up your class by accident. If a property has no effect, check the prefix in the annotation against the key the user typed, because binding is case-insensitive but not spelling-insensitive.

When a starter is too much

If only one service needs the code, a plain @Configuration in that service is simpler and has no release process. A shared library with no Spring dependency should stay free of Spring, with a thin Boot module on top. When a user reports that your starter was not applied, the first tool is the conditions report. The Spring Boot source has many real examples, and the authoring reference is Creating Your Own Starter.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.