4.3 starter 制作步骤
4.3.1 一个完整的Spring Starter库包含以下组件(也可以合并以下组件为一个组件)
- 自动化配置模块
-
4.3.2 Starter 的命名规范
对于Spring 官方的命名: spring-boot-starter-{name} 如: spring-boot-starter-web
- 第三方库的命名: 如果是分开配置模块和启动模块的,
- 配置模块命名为 :{name}-spring-boot-autoconfigure
- 启动器模块: {name}-spring-boot-starter
- 合并的则直接命名{name}-spring-boot-starter;
4.3.3 步骤
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>2.2.0.RELEASE</version><optional>true</optional></dependency>
设置打包方式
<packaging>jar</packaging>
定义属性配置类
//用于在*.properties文件中定义, 如:hello.msg = hello world!@ConfigurationProperties(prefix = "hello")public class HelloProperties {private String msg;public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}
定义自动配置类
@Configuration@ConditionalOnClass({HelloService.class})@EnableConfigurationProperties(HelloProperties.class)public class HelloAutoConfiguration {@Autowiredprivate HelloProperties helloProperties;@ConditionalOnMissingBean({HelloService.class})@Beanpublic HelloService logservice() {return new HelloService(helloProperties.getMsg());}}
定义starter 具体功能
public class HelloService {private String msg;public HelloService(String msg) {this.msg = msg;}public void syaHello() {System.out.println(msg);}}
设置配置类
//(路径:resources/META-INF/spring.factories)//用于Spring使用SPI机制加载配置类org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.hdj.configuration.HelloAutoConfiguration
然后,就可以打jar包,发布到maven 中供其他项目引入使用
