Create a Custom Auto-Configuration with Spring Boot

迷南。 2024-03-25 19:48 151阅读 0赞

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

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. <version>2.4.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <version>8.0.19</version>
  10. </dependency>

Creating a Custom Auto-Configuration

Create a custom auto-configuration 仅需2步
1、create a class annotated as @Configuration
2、把此类注册到约定的路径下

  1. # Step1: Create a custom configuration for a MySQL data source
  2. @Configuration
  3. public class MySQLAutoconfiguration {
  4. //...
  5. }
  6. # Step2: Register the class as an auto-configuration candidate(候选人).
  7. # in the standard file resources/META-INF/spring.factories
  8. 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

发表评论

表情:
评论列表 (有 0 条评论,151人围观)

还没有评论,来说两句吧...

相关阅读