在 Spring Boot 中创建一个自定义的 Starter 涉及到创建一个自动配置模块,包括了一组预选的依赖定义和自动配置类。以下是定义一个自定义 Starter 的步骤:
首先,创建一个新的 Maven 或 Gradle 项目作为自定义 Starter。这个项目将包含自动配置代码和需要的依赖。
starter 依赖在项目的 pom.xml 或 build.gradle 文件中,添加所需的 spring-boot 依赖和你的starter将要提供自动配置的库。
示例 pom.xml 的依赖部分可能如下所示:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-autoconfigureartifactId>
<version>${spring-boot.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
<version>${spring-boot.version}version>
dependency>
<dependency>
<groupId>com.examplegroupId>
<artifactId>example-database-clientartifactId>
<version>${example-client.version}version>
dependency>
dependencies>
确保所依赖的库的版本与 Spring Boot 版本兼容。
在项目中,创建一个带有 @Configuration 注解的类。在这个类中,根据条件添加 Bean 的创建方法。使用 @ConditionalOn 系列注解来确定在何种条件下应用这个配置。
@Configuration
@ConditionalOnClass(ExampleClient.class)
@ConditionalOnProperty(prefix = "example", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(ExampleProperties.class)
public class ExampleAutoConfiguration {
@Autowired
private ExampleProperties properties;
@Bean
@ConditionalOnMissingBean
public ExampleClient exampleClient() {
return new ExampleClient(properties.getUrl(), properties.getUsername(), properties.getPassword());
}
}
ExampleProperties 类会使用 @ConfigurationProperties 来获取配置文件中指定前缀的属性。
@ConfigurationProperties(prefix = "example")
public class ExampleProperties {
private String url;
private String username;
private String password;
// getters and setters
}
resources/META-INF 下创建 spring.factories 文件创建 resources/META-INF/spring.factories 文件,并在该文件中指定你的自动配置类路径。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.ExampleAutoConfiguration
如果需要,你可以提供一个 resources/META-INF/spring-configuration-metadata.json 文件,为用户提供所有支持的配置选项的元数据描述。
{
"groups": [
{
"name": "example",
"type": "com.example.ExampleProperties",
"sourceType": "com.example.ExampleProperties"
}
],
"properties": [
{
"name": "example.url",
"type": "java.lang.String",
"description": "URL to connect to the example service."
},
// 更多属性...
]
}
将这个项目打包成一个 JAR 文件并发布到 Maven 仓库,无论是本地的还是远端的。
用户可以通过将你的 Custom Starter 作为依赖添加到他们的项目中来使用它。由于 Spring Boot 的自动配置机制,包含 Starter 的项目将自动配置为使用相关的库,而且配置可以通过应用的属性文件定制。
-spring-boot-starter 作为后缀,以便清楚地表明它是一个为 Spring Boot 设计的 Starter(遵守官方 Starter 的命名约定)。application.properties 或 `application.yml