Spring auto configuration
What is spring auto-configuration?
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB
is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
or @SpringBootApplication
annotations to one of your @Configuration classes.
Reading material:
-
https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-auto-configuration.html
-
https://docs.spring.io/spring-boot/docs/current/reference/html/auto-configuration-classes.html
Our own auto configuration
If you are working in an organization that relies heavily on Spring Boot and you have common concerns that need to be solved, you can create your own auto-configuration.
This task is more involved, so you need to consider when the benefits are worth the investment. It is easier to maintain a single auto-configuration than multiple bespoke configurations, all slightly different.
If you are publishing your library to open-source, providing a Spring Boot configuration will greatly ease the adoption for thousands of users.
What is a good way to implement it?
Use Spring Boot starter parents
e.g. This varies based on the requirement.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
How to exclude certain features (like spring data jpa) from Spring auto configuration in an application?
It is possible to exclude some classes from the Auto-configuration, by using the following annotation property: @EnableAutoConfiguration(exclude={ClassNotToAutoconfigure.class})
, but you should do it only if absolutely necessary.
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Tags
- Spring Boot starter parents
- Spring auto configuration - Conditional
- Display Auto-Configuration Report in Spring Boot
Reading material
TODO https://www.marcobehler.com/guides/spring-boot-autoconfiguration