构建自己的 Spring Boot Starter
Starter 优势
依赖聚合:Spring Boot Starter 将一系列相关的依赖项打包成一个单一的依赖项,简化了项目的依赖管理。开发者只需引入一个 Starter,即可获得所需的所有相关依赖,无需手动逐一添加。
自动配置:Starter 内置了基于 @Conditional
注解的配置类,能够根据项目的运行环境(例如类路径中是否存在特定的类)自动创建并装配 Bean。这种机制极大地减少了手动配置的工作量,使得开发者能够更专注于业务逻辑的实现。
通过这两大优势,Spring Boot Starter 显著提升了开发效率,降低了配置复杂度,使得项目的搭建和维护更加便捷。
如何构建属于自己 Starter
根据配置自动装配一个SimpleDateFormat
1. 新建 Spring Boot 项目
2. 创建
DateFormatProperties :
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("formatter") // 匹配 formatter 前缀的配置
public class DateFormatProperties {
private String pattern = "yyyy-MM-dd HH:mm:ss";
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
DateFormatConfiguration :
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration
@EnableConfigurationProperties(DateFormatProperties.class) // 扫描 DateFormatProperties,注册为bean
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true") // 当且 formatter.enabled = true 才会被加载
public class DateFormatConfiguration {
private final DateFormatProperties dateFormatProperties;
public DateFormatConfiguration(DateFormatProperties dateFormatProperties) {
this.dateFormatProperties = dateFormatProperties;
}
@Bean(name = "myDateFormatter")
public SimpleDateFormat myDateFormatter() {
return new SimpleDateFormat(dateFormatProperties.getPattern());
}
}
spring.factories : 这里需要替换为实际自己的类路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.tao.config.DateFormatConfiguration
使用maven工具打包成jar包:
mvn clean install
3. 新项目中使用
pom文件中添加依赖:
<dependency>
<groupId>org.tao</groupId>
<artifactId>tao-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
application.properties:
formatter.enabled = true
formatter.pattern = yyyy-MM-dd
启动Spring项目,SimpleDateFormat 就自动被 Spring 进行管理。
总结步骤
- 引入 spring-boot-autoconfigure 依赖
- 创建配置实体类
- 创建自动配置类,设置实例化条件(@Conditionalxxx注解,可不设置),并注入容器
- 在 MATE-INF 文件夹下创建 spring.factories 文件夹,激活自动配置。
- 在 maven 仓库发布 starter
附录
关于Spring 自动装配
2.7.x之前:resources 下增加META-INF文件夹,创建spring.factories
文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.handsometaoa.config.SmsConfig
2.7.x之后:resources 下增加META-INF文件夹,在其下创建spring文件夹,最后创建
org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件
com.handsometaoa.config.SmsConfig
本文来自博客园,作者:帅气的涛啊,转载请注明原文链接:https://www.cnblogs.com/handsometaoa/p/18779874