依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
使用 spring-boot-configuration-processor
配合 @ConfigurationProperties
可以在生成目录下创建 META-INF/spring-configuration-metadata.json
该文件中存放了配置文件的元数据信息。
使用方式
编写Properties类
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.net.InetAddress;
@ConfigurationProperties(prefix = "demo", ignoreUnknownFields = true)
public class DemoProperties {
/**
* 绑定ip
*/
private String bind;
/**
* 网络地址
*/
private InetAddress address;
/**
* 监听端口
*/
private Integer port = 8080;
/**
* 功能开启
*/
private Boolean enable = true;
public String getBind() {
return bind;
}
public void setBind(String bind) {
this.bind = bind;
}
public InetAddress getAddress() {
return address;
}
public void setAddress(InetAddress address) {
this.address = address;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
}
编写Config类,并开启Properties扫描。一般建议把Properties和Config结合起来做成一个模块。
import com.example.demo.properties.DemoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(DemoProperties.class)
public class DemoConfig {
}
使用 mvn compile
编译生成元数据
需要手动设置的元数据
虽然 spring-boot-configuration-processor
会为我们生成一些元数据,但是有时我们需要额外补充一些信息。这时可以在 resources/META-INF
下创建一个 additional-spring-configuration-metadata.json
文件,在里面手工添加补充信息。
文件编写语法参考最后的文档链接。
存在问题
- 在IDEA社区版中,元数据中的中文描述显示时会乱码
- IDEA企业版是否会乱码,未知
- 在STS中不会乱码
参考文档
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/appendix-configuration-metadata.html