Create a Custom Auto-Configuration with Spring Boot
The Spring Boot auto-configuration helps us automatically configure a Spring application based on the dependencies that are present on the classpath
This can make development faster and easier by eliminating the need to define certain beans included in the auto-configuration classes.
In the following section, we’ll look at creating our custom Spring Boot auto-configuration
.
Maven Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
Creating a Custom Auto-Configuration
Create a custom auto-configuration 仅需2步
1、create a class annotated as @Configuration
2、把此类注册到约定的路径下
# Step1: Create a custom configuration for a MySQL data source
@Configuration
public class MySQLAutoconfiguration {
//...
}
# Step2: Register the class as an auto-configuration candidate(候选人).
# in the standard file resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \com.autoconfiguration.MySQLAutoconfiguration
If we want our auto-configuration class to have priority
over other candidates, we can add the @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
annotation.
Note that the auto-configuration
is only in effect if we don’t define the auto-configured beans
in the application. If we define our bean, it will override the default one.
参考: Create a Custom Auto-Configuration with Spring Boot
还没有评论,来说两句吧...