Spring-Boot

springboot-autoconfigure配置提示

2019-12-07  本文已影响0人  nextbeginning

简介

springboot的application.properties或者.yml有对配置自动提示的功能,如果随便写一个不存在的配置,不仅没有提示,而且会有警告,本文简单介绍增加自己的配置的方法。

1.配置文件自动提示原理

spring插件在编写配置的时候,自动扫描jar包中META-INF目录下的spring-configuration-metadata.json文件,解析配置相关信息。
示例文件

{
  "groups": [
    {
      "name": "demo",
      "type": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties",
      "sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties"
    },
    {
      "name": "demo.session",
      "type": "com.example.demo.config.Session",
      "sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties",
      "sourceMethod": "getSession()"
    }
  ],
  "properties": [
    {
      "name": "demo.enbale",
      "type": "java.lang.String",
      "description": "一级配置",
      "sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties"
    },
    {
      "name": "demo.session.session-cookie-key",
      "type": "java.lang.String",
      "description": "sessionId在cookie中存储的key名",
      "sourceType": "com.example.demo.config.Session",
      "defaultValue": "session_token"
    }
  ],
  "hints": []
}
2.配置元数据json串含义解析

springboot可以自动提示的的配置,都是放在properties元素中,如果元素不是基本类型,需要在groups下声明,description为该属性的注释,Tips:这个元数据json文件不需要手动编写,可以自动生成。

3.定义自己的配置类
@ConfigurationProperties(prefix = "demo")
public class DemoConfigurationProperties {

    /** 一级配置*/
    private String name;
    
    /** 引用外部类的配置,需要加@NestedConfigurationProperty注解*/
    @NestedConfigurationProperty
    private Session session = new Session();
    
    Getter and Setter…
}

一般来说自己的配置类写在com.company.xxproject.config包下,然后在com.company.xxproject.spring.boot.autoconfigure包下建一个xxprjectConfigurationProperties类,使用@ConfigurationProperties注解,引用config包下的具体项目配置用@NestedConfigurationProperty。

4.pom文件增加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
5.打包上传

打包后,生成的jar包的META-INF文件下就会自动生成spring-configuration-metadata.json,其他项目引入该包之后,application配置文件就可以自动提示这些配置了

上一篇 下一篇

猜你喜欢

热点阅读