自定义Spring Boot Starter

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

添加依赖


    
        org.springframework.boot
        spring-boot-autoconfigure
        2.1.6.RELEASE
        provided
    
    
        org.springframework.boot
        spring-boot-configuration-processor
        2.1.6.RELEASE
        true
    
    
        org.projectlombok
        lombok
        1.18.8
        true
    


属性配置类

@Data
@ConfigurationProperties(prefix = "tenmao")
public class TenmaoProperties {
    private boolean enabled;
    private String name;
    private String url;
    private Set 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仓库给其他项目使用了

使用


使用方式如下:

  • 添加依赖

    com.tenmao
    tenmao-spring-boot-starter
    1.0-SNAPSHOT

  • 配置信息(application.yml)
tenmao:
  enabled: true
  name: tenmao
  url: http://www.jianshu.com
  hobbies:
    - basketball
    - football
    - pingpong
  • 直接注入就可以使用
@Resource
private TenmaoService tenmaoService;

参考

  • Spring Boot入门教程(三十一): 自定义Starter

你可能感兴趣的:(自定义Spring Boot Starter)