Spring Boot配置文件有提示

在研究spring boot源码时,会在META-INF目录下发现spring-configuration-metadata.json的文件,这个文件用于在配置文件中设置属性值时具有提示功能。这个功能适用于spring boot 2.0以上。

属性说明

groups

"groups"是高级别的节点,它们本身不指定一个值,但为properties提供一个有上下文关联的分组。例如,server.port和server.servlet-path属性是server组的一部分,@ConfigurationProperties注解指定的属性前缀,会自动提示属性名称前缀。

注:不需要每个"property"都有一个"group",一些属性可以以自己的形式存在。

"groups": [
	{
		"name": "server",
		"type": "org.springframework.boot.autoconfigure.web.ServerProperties",
		"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
	},
	{
		"name": "spring.jpa.hibernate",
		"type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
		"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
		"sourceMethod": "getHibernate()"
	}
	...
]

properties

输入属性名称时的提示,即在配置文件中输入属性值,会提示。

"properties": [
	{
		"name": "server.port",
		"type": "java.lang.Integer",
		"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
	},
	{
		  "name": "spring.jpa.hibernate.ddl-auto",
		  "type": "java.lang.String",
		  "description": "DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property.",
		  "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
	}
	...
]

hints

hints描述某个属性的属性值的可选提示。在输入冒号(:)后的提示

    name 属性全名,不能为空 values 可选的值
"hints": [
	{
		"name": "spring.jpa.hibernate.ddl-auto",
		"values": [
			{
				"value": "none",
				"description": "Disable DDL handling."
			},
			{
				"value": "validate",
				"description": "Validate the schema, make no changes to the database."
			}
		]
	}
]

原理

注解解释器

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

需要的注解

    @ConfigurationProperties 配置属性文件,需要指定前缀 prefix @EnableConfigurationProperties 启用配置,需要指定启用的配置类 @NestedConfigurationProperty 当一个类中引用了外部类,需要在该属性上加该注解

注解使用

@ConfigurationProperties(prefix="server")
public class ServerProperties {

	private String name;

	private Host host;

	// ... getter and setters

	public static class Host {

		private String ip;

		private int port;

		// ... getter and setters

	}

}

增加文件

META-INF/additional-spring-configuration-metadata.json

文件中定义groups,attributes,hints

参考

经验分享 程序员 微信小程序 职场和发展