自定义Spring Boot Starter

/ Java / 没有评论 / 1789浏览

使用Spring Boot时,各个starter用起来非常方便。所以我们也可以把自己的一些组件项目封装为starter,方便其他业务系统使用

添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>2.1.6.RELEASE</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <version>2.1.6.RELEASE</version>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
        <optional>true</optional>
    </dependency>
</dependencies>

属性配置类

@Data
@ConfigurationProperties(prefix = "tenmao")
public class TenmaoProperties {
    private boolean enabled;
    private String name;
    private String url;
    private Set<String> hobbies;
}

核心服务类

public class TenmaoService {
    private TenmaoProperties tenmaoProperties;

    public TenmaoService(TenmaoProperties tenmaoProperties) {
        this.tenmaoProperties = tenmaoProperties;
    }

    public void greeting() {
        System.out.printf("tenmao: %s%n", tenmaoProperties);
    }
}

自动配置类

@Configuration
@ConditionalOnClass({TenmaoService.class, TenmaoProperties.class})
@EnableConfigurationProperties({TenmaoProperties.class})
@ConditionalOnProperty(prefix = "tenmao", value = "enabled", matchIfMissing = true)
public class TenmaoAutoConfiguration {
    private final TenmaoProperties tenmaoProperties;

    @Autowired
    public TenmaoAutoConfiguration(TenmaoProperties tenmaoProperties) {
        this.tenmaoProperties = tenmaoProperties;
    }

    @Bean
    @ConditionalOnMissingBean(TenmaoService.class)
    public TenmaoService tenmaoService() {
        return new TenmaoService(tenmaoProperties);
    }
}

现在可以打包发布到maven仓库给其他项目使用了

使用


使用方式如下:

<dependency>
    <groupId>com.tenmao</groupId>
    <artifactId>tenmao-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
tenmao:
  enabled: true
  name: tenmao
  url: http://www.jianshu.com
  hobbies:
    - basketball
    - football
    - pingpong
@Resource
private TenmaoService tenmaoService;

参考