秦皇岛工程建设信息网站,宁德seo培训,已有网站 需要整改 怎么做,爱主题wordpress1、前言Springboot项目配置properties或yaml文件时候#xff0c;会有很多spring相关的配置提示。这个是如何实现的#xff1f;如果我们自己的配置属性#xff0c;能否也自动提示#xff1f;2、Springboot配置自动提示其实IDE是通过读取配置信息的元数据而实现自动提示的。S…1、前言Springboot项目配置properties或yaml文件时候会有很多spring相关的配置提示。这个是如何实现的如果我们自己的配置属性能否也自动提示2、Springboot配置自动提示其实IDE是通过读取配置信息的元数据而实现自动提示的。Springboot的元数据就在目录META-INF下。通过starter部分结构我们可以看到如下其实springboot自动提示元数据就在META-INF中的spring-configuration-metadata.json或additional-spring-configuration-metadata.json。打开additional-spring-configuration-metadata.json可以看到json结构{groups: [],properties: [{name: spring.devtools.add-properties,type: java.lang.Boolean,description: Whether to enable development property defaults.,defaultValue: true}],hints: []
}properties为设置的提示属性name为属性名称type为属性类型defaultValue为该属性默认值description为属性描述。groups为properties提供了一个有上下文关联的分组。本身并不指定一个值。hints为属性设置多个提示值。具体配置描述详见官网地址https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html3、手写尝试1、创建starter工程创建starter模块工程MySpringbootDemoModule12、自动装配创建属性映射类DemoPropertiespackage org.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;EnableConfigurationProperties({DemoProperties.class})
ConfigurationProperties(prefix org.shamee)
public class DemoProperties {private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age age;}
}
创建MyAutoConfigurationpackage org.example;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;Configuration
public class MyAutoConfiguration {Beanpublic DemoProperties demoProperties(){return new DemoProperties();}}
配置spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration\
org.example.MyAutoConfiguration到此一个简单的starter模块就已创建完毕但是此时如果直接使用IDE是无法自动提示的。这里我们期望IDE帮我们自动提示DemoProperties中的两个属性org.shamee.name和org.shamee.age。3、创建元数据那么我们在resources下创建META-INF/additional-spring-configuration-metadata.json并给与配置信息。{properties: [{name: org.shamee.name,type: java.lang.String,defaultValue: test},{name: org.shamee.age,type: java.lang.Integer,defaultValue: 12}]
}4、安装使用到此就已经完成了一个能够让IDE自动帮我们提示的starter依赖。执行mvn install安装。5、使用创建一个主工程MySpringbootDemopom.xml添加上述starter依赖。刷新以来后尝试application.properties上配置我们自定义的属性。可以看到IDE已经自动帮我们提示了属性名称以及默认的值。嗯爽了。看下starter依赖结构好了又白嫖了一个无聊的小知识