美文网首页
编写一个 spring-boot-starter

编写一个 spring-boot-starter

作者: 小一_127b | 来源:发表于2019-11-28 22:43 被阅读0次

按照规范,编写一个 starter 最终会产出两个包,如下

xxx-spring-boot-autoconfigure
xxx-spring-boot-starter

但其实 xxx-spring-boot-starter 这个只是对 xxx-spring-boot-autoconfigure 做了一个引用,实际上干事儿的是 autoconfigure 这个包。下面是以华为Obs对象存储客户端自动配置作为例子,写的一个 starter,在这个starter 中,我将starter和autoconfigure合为一个包了。

  1. 新建一个 maven 项目 obs-spring-boot-starter,并引入相关的依赖;
  2. 创建 ObsProperties 类,用于配置自动注入到容器中组件;
  3. 创建ObsAutoConfiguration,这里可根据一些条件决定是否注入;
  4. 在资源目录下创建文件 META-INF/spring.factories

pom.xml

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
<groupId>com.hanboard.educloud</groupId>
<artifactId>obs-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
......
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.huaweicloud/esdk-obs-java -->
<dependency>
    <groupId>com.huaweicloud</groupId>
    <artifactId>esdk-obs-java</artifactId>
    <version>3.19.7</version>
</dependency>

ObsProperties

@Data
@ConfigurationProperties(prefix = ObsProperties.OBS_PREFIX)
public class ObsProperties {

    public static final String OBS_PREFIX = "obs";

    private String enable = "false";

    private String endPoint;

    private String ak;

    private String sk;
}

ObsAutoConfiguration

@Slf4j
@Configuration
@ConditionalOnClass({ObsClient.class})
@EnableConfigurationProperties(ObsProperties.class)
public class ObsAutoConfiguration {

    private ObsProperties obsProperties;

    public ObsAutoConfiguration(ObsProperties obsProperties) {
        this.obsProperties = obsProperties;
    }

    @Bean
    @ConditionalOnProperty(prefix = ObsProperties.OBS_PREFIX, name = "enable ", havingValue = "true")
    public ObsClient createObsClient() {
        String ak = this.obsProperties.getAk();
        String sk = this.obsProperties.getSk();
        String endPoint = this.obsProperties.getEndPoint();
        return new ObsClient(ak, sk, endPoint);
    }
}

META-INF/spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xxx.autoconfigure.ObsAutoConfiguration

相关文章

网友评论

      本文标题:编写一个 spring-boot-starter

      本文链接:https://www.haomeiwen.com/subject/bvviwctx.html