CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-boot--spring-boot-autoconfigure

Spring Boot AutoConfigure provides auto-configuration capabilities that automatically configure Spring applications based on jar dependencies present on the classpath

Pending
Overview
Eval results
Files

core-annotations.mddocs/reference/

Core Auto-Configuration Annotations

Spring Boot AutoConfigure provides core annotations for enabling and controlling auto-configuration behavior in Spring Boot applications. These annotations work together to intelligently configure Spring applications based on classpath contents and user-defined configurations.

Imports

import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.SpringBootConfiguration;

Primary Annotations

SpringBootApplication

The main application annotation that combines auto-configuration, component scanning, and Spring Boot configuration. This is the most common annotation used to bootstrap a Spring Boot application.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
    @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)
})
public @interface SpringBootApplication {
    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * Since this annotation is parsed by loading class bytecode, it is safe to specify
     * classes that may not be on the classpath, but only if directly on the component.
     * 
     * @return array of auto-configuration classes to exclude (never null, defaults to empty)
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be applied.
     * Use when the class might not be on the classpath at compile time.
     * 
     * @return array of fully-qualified class names to exclude (never null, defaults to empty)
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    String[] excludeName() default {};

    /**
     * Base packages to scan for annotated components.
     * Use scanBasePackageClasses for a type-safe alternative.
     * Note: This has no effect on @Entity scanning or Spring Data repository scanning.
     * Those features use AutoConfigurationPackages to determine base packages.
     * 
     * @return array of base package names (never null, defaults to package of annotated class)
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};

    /**
     * Type-safe alternative to scanBasePackages for specifying packages to scan.
     * The package of each class specified will be scanned.
     * Consider creating a marker class in each package you want to scan.
     * 
     * @return array of classes whose packages will be scanned (never null, defaults to empty)
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};

    /**
     * The BeanNameGenerator class to be used for naming detected components.
     * Defaults to AnnotationBeanNameGenerator which generates names from annotations.
     * 
     * @return the bean name generator class (never null)
     */
    @AliasFor(annotation = ComponentScan.class, attribute = "nameGenerator")
    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    /**
     * Specify whether @Bean methods should get proxied to enforce bean lifecycle behavior.
     * Default is true. Set to false for "Bean Lite Mode" to avoid CGLIB subclass processing.
     * Lite mode disables inter-bean references via method calls.
     * 
     * @return true to proxy bean methods, false for lite mode (default: true)
     */
    @AliasFor(annotation = Configuration.class)
    boolean proxyBeanMethods() default true;
}

Usage example:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

With exclusions:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class
})
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

With custom base packages:

@SpringBootApplication(scanBasePackages = {
    "com.example.app",
    "com.example.shared"
})
public class MyApplication {
    // Application code
}

EnableAutoConfiguration

Enables auto-configuration of the Spring Application Context, attempting to guess and configure beans based on classpath and bean definitions. Usually used through @SpringBootApplication.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    /**
     * Environment property that can be used to override when auto-configuration is enabled.
     * Set "spring.boot.enableautoconfiguration=false" in your environment to disable
     * auto-configuration entirely. This is rarely needed.
     */
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * Safe to specify classes that may not be on the classpath.
     * 
     * @return array of auto-configuration classes to exclude (never null, defaults to empty)
     */
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be applied.
     * Use for classes that might not be available at compile time.
     * 
     * @return array of fully-qualified class names to exclude (never null, defaults to empty)
     */
    String[] excludeName() default {};
}

Usage example (without @SpringBootApplication):

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyConfiguration {
    // Configuration beans
}

Excluding specific auto-configurations:

@EnableAutoConfiguration(exclude = {
    DataSourceAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class MyConfiguration {
    // Custom database configuration
}

AutoConfiguration

Indicates that a class provides configuration that can be automatically applied by Spring Boot. Auto-configuration classes are regular @Configuration classes with proxyBeanMethods set to false. They are located using ImportCandidates from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore
@AutoConfigureAfter
public @interface AutoConfiguration {
    /**
     * Explicitly specify the name of the Spring bean definition.
     * If left unspecified, a bean name will be automatically generated.
     * 
     * @return the bean name (empty string means auto-generate)
     */
    @AliasFor(annotation = Configuration.class)
    String value() default "";

    /**
     * The auto-configuration classes that should have not yet been applied.
     * This configuration will be applied before these classes.
     * Safe to specify classes that may not be on the classpath.
     * 
     * @return array of configuration classes this should run before (never null, defaults to empty)
     */
    @AliasFor(annotation = AutoConfigureBefore.class, attribute = "value")
    Class<?>[] before() default {};

    /**
     * The names of the auto-configuration classes that should have not yet been applied.
     * Use $ to separate nested classes (e.g., com.example.Outer$NestedAutoConfiguration).
     * Useful when you can't reference the class directly.
     * 
     * @return array of configuration class names this should run before (never null, defaults to empty)
     */
    @AliasFor(annotation = AutoConfigureBefore.class, attribute = "name")
    String[] beforeName() default {};

    /**
     * The auto-configuration classes that should have already been applied.
     * This configuration will be applied after these classes.
     * Safe to specify classes that may not be on the classpath.
     * 
     * @return array of configuration classes this should run after (never null, defaults to empty)
     */
    @AliasFor(annotation = AutoConfigureAfter.class, attribute = "value")
    Class<?>[] after() default {};

    /**
     * The names of the auto-configuration classes that should have already been applied.
     * Use $ to separate nested classes (e.g., com.example.Outer$NestedAutoConfiguration).
     * Useful when you can't reference the class directly.
     * 
     * @return array of configuration class names this should run after (never null, defaults to empty)
     */
    @AliasFor(annotation = AutoConfigureAfter.class, attribute = "name")
    String[] afterName() default {};
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@ConditionalOnClass(MyService.class)
public class MyServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyService myService() {
        return new MyService();
    }
}

With ordering:

@AutoConfiguration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@ConditionalOnClass({DataSource.class, MyRepository.class})
public class MyRepositoryAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public MyRepository myRepository(DataSource dataSource) {
        return new MyRepository(dataSource);
    }
}

ImportAutoConfiguration

Imports and applies specified auto-configuration classes. Applies the same ordering rules as @EnableAutoConfiguration but restricts to the specified set. Useful for testing specific auto-configurations.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ImportAutoConfigurationImportSelector.class)
public @interface ImportAutoConfiguration {
    /**
     * The auto-configuration classes that should be imported.
     * This is an alias for classes(). Use either value() or classes(), not both.
     * 
     * @return array of auto-configuration classes (never null, defaults to empty)
     */
    @AliasFor("classes")
    Class<?>[] value() default {};

    /**
     * The auto-configuration classes that should be imported.
     * When empty, classes are specified using a file in META-INF/spring
     * where the file name is the fully-qualified name of the annotated class,
     * suffixed with .imports. An entry may be prefixed with "optional:" to indicate
     * it should be ignored if not on the classpath.
     * 
     * @return array of auto-configuration classes (never null, defaults to empty)
     */
    @AliasFor("value")
    Class<?>[] classes() default {};

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * Useful when you want most auto-configurations from a set but not all.
     * 
     * @return array of classes to exclude (never null, defaults to empty)
     */
    Class<?>[] exclude() default {};
}

Usage example for testing:

import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
@ImportAutoConfiguration(classes = {
    DataSourceAutoConfiguration.class
})
public class MyTestConfiguration {
    // Test configuration
}

Using imports file:

// Create file: META-INF/spring/com.example.MyTest.imports
// Contents:
// com.example.MyAutoConfiguration
// com.example.AnotherAutoConfiguration
// optional:com.example.OptionalAutoConfiguration

@ImportAutoConfiguration
public class MyTest {
    // Test class
}

Ordering Annotations

AutoConfigureBefore

Hint that an auto-configuration should be applied before other specified auto-configuration classes. The order affects only when beans are defined, not when they are created or initialized.

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Documented
public @interface AutoConfigureBefore {
    /**
     * The auto-configuration classes that should have not yet been applied.
     * Safe to specify classes that may not be on the classpath if directly on the component.
     * Spring Boot checks for class presence before evaluating.
     * 
     * @return array of configuration classes (never null, defaults to empty)
     */
    Class<?>[] value() default {};

    /**
     * The names of the auto-configuration classes that should have not yet been applied.
     * Use $ to separate nested classes.
     * Useful when you can't reference the class directly at compile time.
     * 
     * @return array of fully-qualified class names (never null, defaults to empty)
     */
    String[] name() default {};
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@AutoConfiguration
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class MyDataSourceInitializerConfiguration {
    // Configuration that must run before DataSourceAutoConfiguration
}

With multiple ordering constraints:

@AutoConfiguration
@AutoConfigureBefore({
    DataSourceAutoConfiguration.class,
    JpaRepositoriesAutoConfiguration.class
})
public class DatabaseSchemaConfiguration {
    // Runs before both DataSource and JPA setup
}

AutoConfigureAfter

Hint that an auto-configuration should be applied after other specified auto-configuration classes. The order affects only when beans are defined, not when they are created or initialized.

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Documented
public @interface AutoConfigureAfter {
    /**
     * The auto-configuration classes that should have already been applied.
     * Safe to specify classes that may not be on the classpath if directly on the component.
     * Spring Boot checks for class presence before evaluating.
     * 
     * @return array of configuration classes (never null, defaults to empty)
     */
    Class<?>[] value() default {};

    /**
     * The names of the auto-configuration classes that should have already been applied.
     * Use $ to separate nested classes.
     * Useful when you can't reference the class directly at compile time.
     * 
     * @return array of fully-qualified class names (never null, defaults to empty)
     */
    String[] name() default {};
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@AutoConfiguration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MyDataSourceDependentConfiguration {
    // Configuration that depends on DataSourceAutoConfiguration
}

Complex ordering:

@AutoConfiguration
@AutoConfigureAfter({
    DataSourceAutoConfiguration.class,
    FlywayAutoConfiguration.class
})
public class ApplicationDataConfiguration {
    // Runs after both DataSource and Flyway are configured
}

AutoConfigureOrder

Auto-configuration specific variant of Spring Framework's @Order annotation. Allows auto-configuration classes to be ordered among themselves without affecting the order of configuration classes passed to AnnotationConfigApplicationContext directly.

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Documented
public @interface AutoConfigureOrder {
    /**
     * The order value. Lower values have higher priority.
     * Default is Ordered.LOWEST_PRECEDENCE (Integer.MAX_VALUE).
     * Use negative values for higher priority than default.
     * Use Ordered.HIGHEST_PRECEDENCE for maximum priority.
     * 
     * @return the order value (defaults to Ordered.LOWEST_PRECEDENCE)
     */
    int value() default Ordered.LOWEST_PRECEDENCE;
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.core.Ordered;

@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class HighPriorityAutoConfiguration {
    // This configuration will be processed early
}

With explicit order values:

@AutoConfiguration
@AutoConfigureOrder(-100)  // High priority
public class CriticalInfrastructureConfiguration {
    // Core infrastructure setup
}

@AutoConfiguration
@AutoConfigureOrder(100)   // Lower priority
public class ApplicationFeatureConfiguration {
    // Application features
}

Package Management

AutoConfigurationPackage

Registers packages with AutoConfigurationPackages. When no base packages or base package classes are specified, the package of the annotated class is registered. Used by features like JPA entity scanning.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
    /**
     * Base packages that should be registered with AutoConfigurationPackages.
     * Use basePackageClasses for a type-safe alternative.
     * 
     * @return array of base package names (never null, defaults to package of annotated class)
     */
    String[] basePackages() default {};

    /**
     * Type-safe alternative to basePackages for specifying packages to be registered.
     * Consider creating a special no-op marker class in each package.
     * The package of each specified class will be registered.
     * 
     * @return array of marker classes (never null, defaults to empty)
     */
    Class<?>[] basePackageClasses() default {};
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.context.annotation.Configuration;

@Configuration
@AutoConfigurationPackage(basePackages = "com.example.domain")
public class MyConfiguration {
    // Configuration
}

Type-safe package registration:

// Create marker class in package
package com.example.domain;
public final class PackageMarker {
    private PackageMarker() {}
}

// Reference in configuration
@Configuration
@AutoConfigurationPackage(basePackageClasses = PackageMarker.class)
public class MyConfiguration {
    // All entities in com.example.domain will be scanned
}

AutoConfigurationPackages (Utility Class)

Utility class for managing auto-configuration packages. Used to register and retrieve packages for entity scanning and component scanning.

public abstract class AutoConfigurationPackages {
    /**
     * Determine if auto-configuration packages have been registered in the bean factory.
     *
     * @param beanFactory the bean factory to check (must not be null)
     * @return true if packages have been registered, false otherwise
     */
    public static boolean has(BeanFactory beanFactory);

    /**
     * Return the auto-configuration packages registered with the given bean factory.
     * Throws IllegalStateException if no packages have been registered.
     * Used by features like JPA entity scanning and Spring Data repository scanning.
     *
     * @param beanFactory the bean factory (must not be null)
     * @return list of registered package names (never null, never empty if registered)
     * @throws IllegalStateException if no packages have been registered
     */
    public static List<String> get(BeanFactory beanFactory);

    /**
     * Programmatically registers the auto-configuration package names.
     * Usually not needed as @AutoConfigurationPackage handles registration,
     * but can be useful in advanced scenarios.
     *
     * @param registry the bean definition registry (must not be null)
     * @param packageNames the package names to register (must not be null, empty, or contain nulls)
     */
    public static void register(
        BeanDefinitionRegistry registry,
        String... packageNames
    );
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.beans.factory.BeanFactory;
import java.util.List;

public class PackageScanner {
    public List<String> getRegisteredPackages(BeanFactory beanFactory) {
        if (AutoConfigurationPackages.has(beanFactory)) {
            return AutoConfigurationPackages.get(beanFactory);
        }
        return Collections.emptyList();
    }
}

Infrastructure Classes

AutoConfigurationImportSelector

DeferredImportSelector that handles @EnableAutoConfiguration. Can be subclassed for custom variants of @EnableAutoConfiguration. This class is responsible for loading auto-configuration class names from META-INF/spring files and filtering them based on conditions.

public class AutoConfigurationImportSelector
        implements DeferredImportSelector, BeanClassLoaderAware,
                   ResourceLoaderAware, BeanFactoryAware, EnvironmentAware {

    /**
     * Select the imports to be registered.
     * Loads auto-configurations from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
     * and filters based on exclusions and conditions.
     *
     * @param annotationMetadata the annotation metadata of the importing class (never null)
     * @return array of fully-qualified class names to import (never null, may be empty)
     */
    public String[] selectImports(AnnotationMetadata annotationMetadata);

    /**
     * Return a predicate to exclude classes from auto-configuration.
     * Used to filter auto-configurations before they are processed by conditions.
     * Improves startup performance by avoiding unnecessary class loading.
     *
     * @return the exclusion filter predicate (may be null if no filtering needed)
     */
    public Predicate<String> getExclusionFilter();

    /**
     * Set the bean factory. Called by Spring during initialization.
     *
     * @param beanFactory the bean factory (never null)
     * @throws BeansException in case of errors
     */
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException;

    /**
     * Set the bean class loader. Called by Spring during initialization.
     *
     * @param classLoader the class loader (never null)
     */
    public void setBeanClassLoader(ClassLoader classLoader);

    /**
     * Set the environment. Called by Spring during initialization.
     *
     * @param environment the environment (never null)
     */
    public void setEnvironment(Environment environment);

    /**
     * Set the resource loader. Called by Spring during initialization.
     *
     * @param resourceLoader the resource loader (never null)
     */
    public void setResourceLoader(ResourceLoader resourceLoader);

    /**
     * Get the order for this import selector.
     * Returns Ordered.LOWEST_PRECEDENCE - 1 to run before user configurations.
     *
     * @return the order value
     */
    public int getOrder();
}

AutoConfigurationExcludeFilter

A TypeFilter implementation that matches registered auto-configuration classes. Used to exclude auto-configuration classes from component scanning to prevent double registration.

public class AutoConfigurationExcludeFilter
        implements TypeFilter, BeanClassLoaderAware {

    /**
     * Set the bean class loader. Called by Spring during initialization.
     *
     * @param beanClassLoader the class loader (never null)
     */
    public void setBeanClassLoader(ClassLoader beanClassLoader);

    /**
     * Determine whether this filter matches for the given metadata.
     * Returns true if the class is a registered auto-configuration.
     *
     * @param metadataReader the metadata reader for the target class (never null)
     * @param metadataReaderFactory factory for reading metadata (never null)
     * @return true if the class should be excluded from scanning, false otherwise
     * @throws IOException in case of I/O errors
     */
    public boolean match(
        MetadataReader metadataReader,
        MetadataReaderFactory metadataReaderFactory
    ) throws IOException;
}

AutoConfigurations (Configuration Class)

Configurations representing auto-configuration @Configuration classes. Used primarily for testing to specify which auto-configurations should be loaded.

public class AutoConfigurations extends Configurations {
    /**
     * Create a new AutoConfigurations instance with the specified classes.
     * The classes are treated as auto-configurations and will be ordered accordingly.
     *
     * @param classes the auto-configuration classes (must not be null or contain nulls)
     * @return new AutoConfigurations instance (never null)
     */
    public static AutoConfigurations of(Class<?>... classes);

    /**
     * Get the order for these configurations.
     * Returns 0 to ensure auto-configurations are ordered among themselves.
     *
     * @return the order value (always 0)
     */
    public int getOrder();
}

Usage example:

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;

public class MyAutoConfigurationTest {
    private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(MyAutoConfiguration.class));

    @Test
    public void testAutoConfiguration() {
        contextRunner.run(context -> {
            assertThat(context).hasSingleBean(MyService.class);
            assertThat(context.getBean(MyService.class))
                .isNotNull()
                .isInstanceOf(MyServiceImpl.class);
        });
    }
    
    @Test
    public void testAutoConfigurationWithProperty() {
        contextRunner
            .withPropertyValues("app.feature.enabled=true")
            .run(context -> {
                assertThat(context).hasBean("featureService");
            });
    }
}

Events and Listeners

AutoConfigurationImportEvent

Event fired when auto-configuration classes are imported. Contains information about candidate configurations and exclusions. Useful for monitoring and debugging auto-configuration loading.

public class AutoConfigurationImportEvent extends ApplicationEvent {
    /**
     * Create a new AutoConfigurationImportEvent.
     *
     * @param source the event source (never null)
     * @param candidateConfigurations the candidate configurations that were considered (never null)
     * @param exclusions the exclusions that were applied (never null)
     */
    public AutoConfigurationImportEvent(
        Object source,
        List<String> candidateConfigurations,
        Set<String> exclusions
    );

    /**
     * Return the candidate auto-configuration classes that were considered for import.
     * Includes all auto-configurations found, even if excluded.
     *
     * @return list of candidate configuration class names (never null, immutable)
     */
    public List<String> getCandidateConfigurations();

    /**
     * Return the exclusions that were applied to filter auto-configurations.
     * Includes both explicit exclusions and those excluded by conditions.
     *
     * @return set of excluded configuration class names (never null, immutable)
     */
    public Set<String> getExclusions();
}

AutoConfigurationImportListener

Listener that can be registered in spring.factories to receive details of imported auto-configurations. May implement various Aware interfaces to receive dependencies. Useful for custom monitoring or logging.

public interface AutoConfigurationImportListener extends EventListener {
    /**
     * Handle an auto-configuration import event.
     * Called after auto-configurations have been selected but before they are processed.
     * Implementations should be fast as this is on the critical startup path.
     *
     * @param event the event containing import details (never null)
     */
    void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event);
}

Register in META-INF/spring.factories:

org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
com.example.MyAutoConfigurationImportListener

AutoConfigurationImportFilter

Filter that can be registered in spring.factories to limit auto-configuration classes considered. Designed for fast removal before bytecode is read, improving startup performance.

public interface AutoConfigurationImportFilter {
    /**
     * Return true for configurations that should be imported.
     * The autoConfigurationMetadata parameter provides access to metadata
     * written by the auto-configure annotation processor, enabling fast filtering
     * without loading classes.
     *
     * This method is called very early and should be extremely fast.
     * Avoid expensive operations like class loading or reflection.
     *
     * @param autoConfigurationClasses the auto-configuration classes to filter (never null)
     * @param autoConfigurationMetadata metadata about the auto-configurations (never null)
     * @return boolean array with true for each class that should be imported (never null, same length as input)
     */
    boolean[] match(
        String[] autoConfigurationClasses,
        AutoConfigurationMetadata autoConfigurationMetadata
    );
}

Register in META-INF/spring.factories:

org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
com.example.MyAutoConfigurationImportFilter

Metadata Support

AutoConfigurationMetadata

Provides access to metadata written by the auto-configure annotation processor. Used for efficient filtering of auto-configurations without loading classes. The metadata is loaded from META-INF/spring-autoconfigure-metadata.properties.

public interface AutoConfigurationMetadata {
    /**
     * Return true if the specified class was processed by the annotation processor.
     *
     * @param className the fully-qualified class name (never null)
     * @return true if the class was processed, false otherwise
     */
    boolean wasProcessed(String className);

    /**
     * Get an integer value from the metadata.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @return the integer value or null if not found
     */
    Integer getInteger(String className, String key);

    /**
     * Get an integer value from the metadata with a default.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @param defaultValue the default value to return if not found
     * @return the integer value or default if not found
     */
    Integer getInteger(String className, String key, Integer defaultValue);

    /**
     * Get a set of values from the metadata.
     * Useful for retrieving lists of conditions or dependencies.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @return set of values or null if not found
     */
    Set<String> getSet(String className, String key);

    /**
     * Get a set of values from the metadata with a default.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @param defaultValue the default value to return if not found
     * @return set of values or default if not found
     */
    Set<String> getSet(String className, String key, Set<String> defaultValue);

    /**
     * Get a value from the metadata.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @return the value or null if not found
     */
    String get(String className, String key);

    /**
     * Get a value from the metadata with a default.
     *
     * @param className the class name (never null)
     * @param key the metadata key (never null)
     * @param defaultValue the default value to return if not found
     * @return the value or default if not found
     */
    String get(String className, String key, String defaultValue);
}

Base Classes

AbstractDependsOnBeanFactoryPostProcessor

Base class for BeanFactoryPostProcessor implementations that can be used to dynamically declare that beans should "depend on" one or more beans. Useful for ensuring initialization order.

public abstract class AbstractDependsOnBeanFactoryPostProcessor
        implements BeanFactoryPostProcessor, Ordered {

    /**
     * Process the bean factory after its initialization.
     * Adds dependencies to matching beans to ensure proper initialization order.
     *
     * @param beanFactory the bean factory (never null)
     * @throws BeansException in case of errors
     */
    public void postProcessBeanFactory(
        ConfigurableListableBeanFactory beanFactory
    ) throws BeansException;

    /**
     * Get the order value of this object.
     * Default is Ordered.LOWEST_PRECEDENCE to run after most other post-processors.
     *
     * @return the order value
     */
    public int getOrder();

    /**
     * Return the bean types that should have the dependency added.
     * Must be implemented by subclasses.
     *
     * @return the bean class that needs the dependency (never null)
     */
    protected abstract Class<?> getBeanClass();

    /**
     * Return the name of the bean that the target beans should depend on.
     * Must be implemented by subclasses.
     *
     * @return the bean name to depend on (never null)
     */
    protected abstract String getDependsOn();
}

Usage example:

import org.springframework.boot.autoconfigure.AbstractDependsOnBeanFactoryPostProcessor;

public class MyDependsOnPostProcessor
        extends AbstractDependsOnBeanFactoryPostProcessor {

    @Override
    protected Class<?> getBeanClass() {
        return MyService.class;
    }

    @Override
    protected String getDependsOn() {
        return "myInitializerBean";
    }
}

Register in configuration:

@Configuration
public class DependencyOrderingConfiguration {
    
    @Bean
    public static MyDependsOnPostProcessor myDependsOnPostProcessor() {
        return new MyDependsOnPostProcessor();
    }
}

Advanced Usage Examples

Custom Auto-Configuration with Ordering

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@ConditionalOnClass(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MyDatabaseAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DatabaseInitializer databaseInitializer(DataSource dataSource) {
        return new DatabaseInitializer(dataSource);
    }

    @Bean
    public DatabaseHealthIndicator databaseHealthIndicator(
            DatabaseInitializer initializer) {
        return new DatabaseHealthIndicator(initializer);
    }
}

Programmatic Package Registration

import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class MyPackageRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(
            AnnotationMetadata metadata,
            BeanDefinitionRegistry registry) {

        AutoConfigurationPackages.register(
            registry,
            "com.example.domain",
            "com.example.repositories"
        );
    }
}

Custom Import Listener

import org.springframework.boot.autoconfigure.AutoConfigurationImportEvent;
import org.springframework.boot.autoconfigure.AutoConfigurationImportListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyAutoConfigurationImportListener
        implements AutoConfigurationImportListener {
    
    private static final Logger logger = 
        LoggerFactory.getLogger(MyAutoConfigurationImportListener.class);

    @Override
    public void onAutoConfigurationImportEvent(
            AutoConfigurationImportEvent event) {

        List<String> candidates = event.getCandidateConfigurations();
        Set<String> exclusions = event.getExclusions();

        logger.info("Loaded {} auto-configurations", candidates.size());
        logger.info("Excluded {} auto-configurations", exclusions.size());
        
        if (logger.isDebugEnabled()) {
            candidates.forEach(c -> logger.debug("Candidate: {}", c));
            exclusions.forEach(e -> logger.debug("Excluded: {}", e));
        }
    }
}

Custom Import Filter

import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter;
import org.springframework.boot.autoconfigure.AutoConfigurationMetadata;

public class MyAutoConfigurationImportFilter
        implements AutoConfigurationImportFilter {

    @Override
    public boolean[] match(
            String[] autoConfigurationClasses,
            AutoConfigurationMetadata autoConfigurationMetadata) {
        
        boolean[] matches = new boolean[autoConfigurationClasses.length];
        
        for (int i = 0; i < autoConfigurationClasses.length; i++) {
            String className = autoConfigurationClasses[i];
            
            // Fast filter based on metadata without loading classes
            boolean shouldInclude = !className.contains("Reactive") ||
                                  isReactiveEnabled(autoConfigurationMetadata, className);
            
            matches[i] = shouldInclude;
        }
        
        return matches;
    }
    
    private boolean isReactiveEnabled(
            AutoConfigurationMetadata metadata,
            String className) {
        // Check metadata for reactive flag
        return "true".equals(metadata.get(className, "reactive"));
    }
}

Best Practices

1. Annotation Placement

Place @SpringBootApplication only on the main application class:

// Good: Single main class
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// Bad: Multiple @SpringBootApplication classes
// Leads to confusion and potential issues

2. Custom Auto-Configuration Registration

Register custom auto-configurations in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:

com.example.MyAutoConfiguration
com.example.AnotherAutoConfiguration

3. Conditional Logic

Use specific conditions rather than @ConditionalOnExpression:

// Good: Type-safe and performant
@ConditionalOnClass(name = "com.example.MyService")
@ConditionalOnProperty(prefix = "app", name = "enabled")

// Avoid: Slower and error-prone
@ConditionalOnExpression("${app.enabled:false} and T(com.example.MyService).exists()")

4. Testing Auto-Configurations

@Test
void autoConfigurationIsApplied() {
    contextRunner
        .withUserConfiguration(UserConfiguration.class)
        .withPropertyValues("app.feature.enabled=true")
        .run(context -> {
            assertThat(context).hasBean("myService");
            assertThat(context.getBean(MyService.class))
                .isNotNull();
        });
}

See Also

  • Conditional Annotations - Controlling when configurations apply
  • Creating Custom Auto-Configurations
  • Testing Auto-Configurations

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework-boot--spring-boot-autoconfigure@4.0.1

docs

index.md

tile.json