实现SpringBootStarter!

实现一个Starter:

  • Starter 命名。
  • 自动配置类,用来初始化相关的 bean。
  • 指明自动配置类的配置文件 spring.factories
  • 自定义属性实体类,声明 starter 的应用配置属性。

名字:

官方的 starter 的命名格式为 spring-boot-starter-{name}

非官方的 starter 的命名格式为 {name}-spring-boot-starter

把自定义的 starter 命名为 fish-spring-boot-starter,命名在 pom 文件里。

1
2
3
4
<groupId>fish.springcloud</groupId>
<artifactId>fish-spring-boot-starter</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

引入自动配置包及其它相关依赖包:

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>

创建 spring.factories 文件:

resource/META-INF 目录下创建名称为 spring.factories 的文件。

当 Spring Boot 启动的时候,会在 classpath 下寻找所有名称为 spring.factories 的文件。

然后运行里面的配置指定的自动加载类,将指定类(一个或多个)中的相关 bean 初始化。

1
2
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
kite.springcloud.boot.starter.example.FishAutoConfigure

编写自动配置类:

自动配置类是用来初始化 starter 中的相关 bean 的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@ConditionalOnClass(FishService.class)
@EnableConfigurationProperties(FishProperties.class)
@Slf4j
public class FishAutoConfigure {

@Autowired
private FishProperties fishProperties;

@Bean
@ConditionalOnMissingBean(FishService.class)
@ConditionalOnProperty(prefix = "fish.example",value = "enabled", havingValue = "true")
FishService fishService(){
return new FishService(fishProperties);
}
}

实现属性配置类:

1
2
3
4
5
6
7
8
@Data
@ConfigurationProperties("fish.example")
public class FishProperties {

private String host;

private int port;
}

实现相关功能类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Slf4j
public class FishService {

private String host;

private int port;

public FishService(FishProperties fishProperties){
this.host = fishProperties.getHost();
this.port = fishProperties.getPort();
}

public void print(){
log.info(this.host + ":" +this.port);
}
}

打包:

通过 maven mvn install命令将 starter 安装到本地 maven 仓库。

也可以通过 mvn package deploy 发布到私服或者发布到中央仓库。