09月12, 2019

springboot系列之自定义starter实例

[TOC]

1.1 新建项目,并添加依赖

<groupId>demo</groupId>
<artifactId>demo-spring-starter</artifactId>
<version>0.0.1</version>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

制作start必须添加spring-boot-configuration-processor

1.2 构造配置类

@Data
@ConfigurationProperties(prefix = "startkit")
public class StartkitProperties {
    private String            name;
    private List<String>    titles;
    private int                times    = -1;
    private boolean            enable    = false;
}

1.3 构造实现业务类

@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class StartkitService {
    private StartkitProperties startkitProperties;

    public Object showLog() {
        log.info("startkitProperties = {}", startkitProperties);
        return startkitProperties;
    }
}

1.4 构造启动配置类

@Configuration
@EnableConfigurationProperties(StartkitProperties.class)
public class AutoStartkitConfiguration {
    @Autowired
    private StartkitProperties startkitProperties;

    @Bean
    public StartkitService startkitService() {
        return new StartkitService(startkitProperties);
    }
}

1.5. 启动配置

src/main/resources/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
demo.startkit.config.AutoStartkitConfiguration

2.1 新项目添加上面的依赖

<groupId>demo</groupId>
<artifactId>demo-spring-starter</artifactId>
<version>0.0.1</version>

2.2 添加相关配置信息

application.yml

startkit:
  name: startKit-名称
  enable: false
  times: 99
  titles:
   - a1
   - b2

2.3 如何禁用

@SpringBootApplication(exclude = AutoStartkitConfiguration.class)

本文链接:https://blog.jnliok.com/post/springboot-new-starter.html

-- EOF --

Comments