AutoConfiguration

  • Allows library developers to automatically configure beans in the Spring context based on different conditions of the application:
    • presence of certain classes in the classpath
    • existence of a bean
    • activation of some property.
  • The AutoConfiguration mechanism is guaranteed to occur after all the user-defined beans have been registered.
  • We can define our own bean and override the default behavior

Config

  • You can disable custom auto-configuration classes in @SpringBootApplication
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
// or if using without @SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
}

Create Custom AutoConfiguration

  • Classes that implement auto-configuration are annotated with @AutoConfiguration
  • This annotation itself is meta-annotated with @Configuration
  • You need to define auto-configuration classes in META-INF directory
  • In Spring Boot 3, it is:
    • resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    • Add list of classes implementing auto-configuration
com.by.kafka.consumer.config.KafkaConsumerAutoConfiguration
com.mycorp.libx.autoconfigure.LibXAutoConfiguration