编写一个 spring-boot-starter

按照规范,编写一个 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

4.0.0

    org.springframework.boot
    spring-boot-starter-parent
    1.5.8.RELEASE

com.hanboard.educloud
obs-spring-boot-starter
1.0-SNAPSHOT
......

    org.projectlombok
    lombok
    provided


    org.springframework.boot
    spring-boot-autoconfigure
    true


    org.springframework.boot
    spring-boot-configuration-processor
    true



    com.huaweicloud
    esdk-obs-java
    3.19.7

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)