自定义springboot starter

背景

项目里使用一些自定义的配置,在bootstrap.yaml里,这些配置会带着黄色的背景色;所以我在想,有没有一种合理的方式可以弄掉背景色。然后发现了springboot-starter。

根据官方文档的说明:

You can easily generate your own configuration metadata file from items annotated with @ConfigurationProperties by using the spring-boot-configuration-processor jar. The jar includes a Java annotation processor which is invoked as your project is compiled. To use the processor, include a dependency on spring-boot-configuration-processor.

您可以使用spring-boot-configuration-processor jar从带有@ConfigurationProperties注释的项目中轻松生成自己的配置元数据文件。 该jar包含一个Java注释处理器,在您的项目被编译时会被调用。 要使用处理器,请包括对spring-boot-configuration-processor的依赖。

明白以上机制后接下来just do it!

1.添加依赖

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

2.添加配置元数据类

@ConfigurationProperties(prefix = "my")
public class MyProperties {
 
    private String property;
 
    private StandardCopyOption copyOption;
 
    public String getProperty() {
        return property;
    }
 
    public void setProperty(String property) {
        this.property = property;
    }
 
    public StandardCopyOption getCopyOption() {
        return copyOption;
    }
 
    public void setCopyOption(StandardCopyOption copyOption) {
        this.copyOption = copyOption;
    }
    
}

3.添加配置类

@Configuration
@EnableConfigurationProperties({MyProperties.class})
public class ApplicationConfiguration {
 
    public MyProperties getMyProperties(MyProperties myProperties) {
        return myProperties;
    }
 
    public void setMyProperties(MyProperties myProperties) {
        this.myProperties = myProperties;
    }
}

在 META-INF 目录下创建 spring.factories,springboot 自动化配置最终就是要扫描 META-INF/spring.factories 来加载项目的自动化配置类。

spring.factories配置文件内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration= ApplicationConfiguration

运行 mvn:install 打包,一个springboot-starter就弄好了。

测试并通过。以上。