Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 66 ยท Auto-Configuration and Configuration

Writing Your Own Starter

Build a custom Spring Boot starter: the autoconfigure module, a properties class, the imports file, metadata, back-off conditions and ApplicationContextRunner tests.

A starter is how Spring Boot packages "everything you need for X" into one dependency. When you add spring-boot-starter-web, Boot's auto-configuration notices Tomcat and Spring MVC on the classpath and creates the right beans. Nothing stops you from using the same mechanism for your own code. A company that has a shared audit library, a payment client or a standard security setup can ship it as a starter, so every team gets a working default with a single dependency line.

In the previous lesson you saw how auto-configuration classes are discovered and how conditions decide which of them apply. This lesson puts that knowledge to work: you design a small starter for a hypothetical greeter library, learn which files it needs, and test it the way Boot itself tests its own auto-configurations.

The real Spring Boot cannot run in our sandbox, so the Spring code below is read-only. Two runnable plain-Java stand-ins rebuild the discovery and testing machinery in miniature, and the text says what is real and what is imitation.

What a starter is made of

A starter is not a special file type. It is a convention for two small artifacts, and many teams collapse them into one.

The parts of a starter

Your library Plain classes that work without Spring.
Auto-configuration A class that creates beans when conditions hold.
Properties class Typed settings under your own prefix.
Imports file A text file that lists the auto-configuration.

The starter jar itself can be an empty pom that pulls these in.

1 / 2

Boot's own split is spring-boot-autoconfigure (code) plus many spring-boot-starter-* poms (dependency lists). For an internal starter, one module is fine until you need optional dependencies. A common naming rule: Boot reserves spring-boot-starter-* for itself, so yours should be acme-spring-boot-starter (your name first).

The library and its properties

The library has no idea Spring exists. That keeps it testable and usable outside Boot.

Java
package com.acme.greeter;

public class Greeter {

    private final String prefix;
    private final String suffix;

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

    public String greet(String name) {
        return prefix + ", " + name + suffix;
    }
}

Settings go in a properties class under your own prefix. A record works well because the values never change after binding. Lesson Type-Safe @ConfigurationProperties covers binding in depth.

Java
package com.acme.greeter.autoconfigure;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;

@ConfigurationProperties(prefix = "acme.greeter")
public record GreeterProperties(
        @DefaultValue("true") boolean enabled,
        @DefaultValue("Hello") String prefix,
        @DefaultValue("!") String suffix) {
}

Choose a prefix that cannot clash with Boot's own namespaces (spring, server, management) or with other libraries. The company name is a safe choice.

The auto-configuration class

This is the heart of the starter. It creates the bean, but only when it makes sense, and it never overrides what the application already defined.

Java
package com.acme.greeter.autoconfigure;

import com.acme.greeter.Greeter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@ConditionalOnClass(Greeter.class)
@ConditionalOnProperty(prefix = "acme.greeter", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(GreeterProperties.class)
public class GreeterAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public Greeter greeter(GreeterProperties properties) {
        return new Greeter(properties.prefix(), properties.suffix());
    }
}

Three conditions appear here, and each one earns its place:

  • @ConditionalOnClass makes the whole configuration inert when the library is not on the classpath.
  • @ConditionalOnProperty with matchIfMissing = true gives users an off switch while keeping the feature on by default.
  • @ConditionalOnMissingBean is the back-off: if the application declares its own Greeter, yours steps aside. This is what makes starters feel friendly, because replacing a default never means fighting it.

Use @AutoConfiguration, not @Configuration. It marks the class as an auto-configuration (so it is processed after user configuration) and lets you order classes with after and before.

Never put @ComponentScan on an auto-configuration class, and do not place it in a package your users' @SpringBootApplication will scan. Component scanning would pick it up as an ordinary configuration, bypass the conditions and the ordering, and make it impossible to exclude cleanly.

The imports file

How does Boot find GreeterAutoConfiguration? Through a plain text file with one fully qualified class name per line, at a fixed path inside your jar:

TEXT
# src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.acme.greeter.autoconfigure.GreeterAutoConfiguration

Lines starting with # are comments. Boot reads this file from every jar on the classpath, merges the lists, removes excluded entries and then evaluates the conditions. The older spring.factories mechanism for auto-configuration was removed in Boot 3, so you will only see it in legacy projects.

The next TryIt rebuilds this discovery in plain Java. A text block plays the role of the imports file, a registry maps names to classes (the real container loads classes by name instead), and the engine applies the conditions in order. Notice that user-defined beans are registered first, so the back-off works.

Java Imports file, conditions and back-off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the order (user beans, then auto-configuration), the text file with one class per line, and the three outcomes of created, skipped and backed off. What is the stand-in: the real container loads classes by name with a class loader, evaluates conditions with a rich annotation model, and binds properties with relaxed rules.

Metadata for IDE completion

Users of your starter will type acme.greeter. in application.yml and expect their IDE to complete the keys and show descriptions. That works through a JSON file, META-INF/spring-configuration-metadata.json, generated at compile time by the configuration processor. Add it as an annotation processor (Maven shown):

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

The processor reads your properties class: field names become keys, types become value hints and Javadoc comments become descriptions. Write that Javadoc for your users:

Java
/**
 * Settings of the greeter starter.
 *
 * @param enabled whether the greeter bean is created
 * @param prefix text placed before the name
 * @param suffix text placed after the name
 */

For keys the processor cannot see (for example, values read with Environment), or to add deprecation notes and allowed values, put hand-written entries in META-INF/additional-spring-configuration-metadata.json.

Testing with ApplicationContextRunner

Booting a full application to test one auto-configuration is slow and noisy. Boot ships ApplicationContextRunner, a tiny harness that builds a lightweight context from exactly the configurations you list, applies property values, runs your assertions and closes the context. Boot's own auto-configurations are tested this way. This is real test code, shown read-only:

Java
class GreeterAutoConfigurationTests {

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

    @Test
    void createsGreeterByDefault() {
        runner.run(context -> {
            assertThat(context).hasSingleBean(Greeter.class);
            assertThat(context.getBean(Greeter.class).greet("Ada")).isEqualTo("Hello, Ada!");
        });
    }

    @Test
    void backsOffWhenUserDefinesGreeter() {
        runner.withBean("custom", Greeter.class, () -> new Greeter("Yo", "?"))
              .run(context -> assertThat(context).hasSingleBean(Greeter.class)
                      .getBean("custom").isNotNull());
    }

    @Test
    void canBeDisabled() {
        runner.withPropertyValues("acme.greeter.enabled=false")
              .run(context -> assertThat(context).doesNotHaveBean(Greeter.class));
    }

    @Test
    void staysOutWhenLibraryIsMissing() {
        runner.withClassLoader(new FilteredClassLoader(Greeter.class))
              .run(context -> assertThat(context).doesNotHaveBean("greeter"));
    }
}

Each test covers one branch of the conditions: default, back-off, property switch and missing class. FilteredClassLoader hides a class from the context, which is how you test @ConditionalOnClass without removing a jar.

The runner is immutable: each with... call returns a new runner, so a shared field is safe. The next TryIt builds that design, a fluent immutable runner with withPropertyValues, withBean and run, and uses it to test the stand-in configuration from before.

Java A runner stand-in for testing starters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real ApplicationContextRunner creates genuine Spring contexts and supports assertThat(context) assertions, failure inspection with hasFailed() and class-loader filtering. The stand-in only keeps the shape: configure fluently, run, assert.

Pitfalls when shipping a starter

  • Back off everywhere. Put @ConditionalOnMissingBean on every bean a user might want to replace. A starter that cannot be overridden gets removed from projects.
  • Guard optional integrations. A bean that needs Micrometer belongs in a nested @Configuration with @ConditionalOnClass(MeterRegistry.class), so the starter works without Micrometer on the classpath.
  • Keep it quiet. Auto-configuration should not start threads, open connections or log at INFO unless the user enabled the feature.
  • Document the keys. Metadata with real descriptions is the difference between a starter people trust and one they avoid.
  • Run the debug report. Start a test app with --debug to see your configuration listed under "positive matches" or "negative matches" with the reason.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file tells Spring Boot where your auto-configuration class is?

    The imports file lists one fully qualified class name per line. Boot reads it from every jar. Component scanning must not be used for auto-configuration.
  2. 2. What does @ConditionalOnMissingBean on a starter's bean achieve?

    User configuration is processed first, so the condition sees the user's bean and skips the default. That makes defaults easy to replace.
  3. 3. Why test an auto-configuration with ApplicationContextRunner instead of @SpringBootTest?

    The runner creates lightweight contexts, applies property values and class-loader filters, and closes them after the assertions.
  4. 4. Where do the IDE hints for acme.greeter.* keys come from?

    The spring-boot-configuration-processor reads your properties class at compile time and writes META-INF/spring-configuration-metadata.json.

Summary

  • A starter is your library plus an auto-configuration class, a properties class and an imports file; the starter pom itself may just list dependencies.
  • Use @AutoConfiguration with conditions: @ConditionalOnClass, @ConditionalOnProperty and @ConditionalOnMissingBean for back-off.
  • List the class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports; never rely on component scanning.
  • Generate configuration metadata so users get completion and descriptions for your keys.
  • Test every branch with ApplicationContextRunner and FilteredClassLoader.

Next: Properties, YAML and Externalized Config.