0
点赞
收藏
分享

微信扫一扫

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)


一、SpringBoot配置介绍

SpringBoot支持两种配置文件类型:

  • application.properties
  • applicatioin.yml

@ConfigurationProperties注解的作用是:把properties或者yml配置文件转化为bean来使用。
@EnableConfigurationProperties注解的作用是:使 使用 @ConfigurationProperties 注解的类生效。

如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的,当然在@ConfigurationProperties加入注解的类上加@Component也可以使交于springboot管理。

所以也就有两种自定义配置的绑定方式:

  • @ConfigurationProperties + @Component
  • @ConfigurationProperties + @EnableConfigurationProperties

另外, @EnableConfigurationProperties 就相当于把使用 @ConfigurationProperties 注解的类(TestProp)进行了一次注入

二、yaml

1、基本语法

  1. 大小写敏感
  2. 使用缩进表示层级关系
  3. 缩进不允许使用tab,只允许空格
  4. 缩进的空格数不重要,只要相同层级的元素左对齐即可
  5. '#'表示注释

2、数据类型

  1. 对象:键值对数据,又称哈希(Hash)、映射(Mapping)、字典(Dict)。
  2. 数组:一组按次序排列的值,又称为序列(sequence)、列表(list)
  3. 常量(scalars):单个的、不可再分的值;比如:字符串(str)、布尔值(bool)、整数(int)、浮点数(float)、时间(time)、日期(date)、Null。

1)对象

对象键值对使用冒号结构表示 ​​key: value​​​,冒号后面需要加一个空格。另外​​key: value​​​可以嵌套使用,例如:​​key: {key1: value1, key2: value2, ...}​​。此外还可以使用缩进表示层级关系。

key: 
child-key1: value1
child-key2:

对应的JSON字符串:

key: {child-key1: value1, child-key2: value2}

2)数组

以​​-​​开头的行表示构成一个数组:

ip: 
- 192.168.1.1
- 192.168.1.2
- 192.168.1.3
-

YAML 支持多维数组,可以使用行内表示:

ip: ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']

对应的JSON字符串:

{ip: ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']}

3)复合(嵌套)结构

users:
-
id: 1
name: Saint
-
id: 2
name: Bob
address:
city: nanjing
street:

意思是 users属性是一个数组,每一个数组元素又是由 id、name、name两个属性构成;address是一个对象。

数组也可以使用流式的方式表示:

users: [{id: 1,name: Saint},{id: 2,name: Bob}]
address:
cite: nanjing
street:

对应的JSON字符串:

{users: [{id: 1,name: Saint},{id: 2,name: Bob}], address:{city: nanjing, street: shazhou}}

4)常量

boolean: 
- TRUE #true,True都可以
- FALSE #false,False都可以
float:
- 3.14
- 6.8523015e+5 #可以使用科学计数法
int:
- 123
- 0b1010_0111_0100_1010_1110 #二进制表示
null:
nodeName: 'node'
parent: ~ #使用~表示null
string:
- 哈哈
- 'Hello world' #可以使用双引号或者单引号包裹特殊字符
- newline
newline2 #字符串可以拆成多行,每一行会被转化成一个空格
date:
- 2018/02/17 ##格式必须为yyyy/M/d 或 yyyy/MM/dd,否则无法在SpringBoot做映射
datetime:
- 2018/02/17 15:02:31 #格式必须为yyyy/M/d HH:mm:ss

5)& 锚点、 * 别名、<< 表示合并到当前数据

​& ​​​用来建立锚点(default),​​<<​​​ 表示合并到当前数据,​​*​​ 用来引用锚点。

& 锚点和 * 别名,可以用来引用:

default: &default # 定义锚点
adapter: postgres
host: localhost

development:
database: myapp_development
<<: *default # 引用锚点 并合并到当前数据

test:
database: myapp_test
<<: *default

相当于:

defaults:
adapter: postgres
host: localhost

development:
database: myapp_development
adapter: postgres
host: localhost

test:
database: myapp_test
adapter: postgres
host:

再来看一种使用方式:

- &showell Steve 
- Saint
- Oren
- *showell

相当于:

[ 'Steve', 'Saint', 'Oren', 'Steve' ]

三、Spring+yaml结合使用案例

首先要在maven依赖中添加:

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

否则TestProp类上会有一行红色的异常信息,具体如下:

Spring Boot Configuration Annotation Processor

并且在pom中加上​​spring-boot-configuration-processor​​​依赖之后,我们使用​​@ConfigurationProperties​​注解注释的配置类中的字段,可以在yaml文件中通过.的方式自动带出提示。

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_spring

1、TestController类(@EnableConfigurationProperties):

@EnableConfigurationProperties(TestProp.class)
@RestController
public class TestController {
@Autowired
private TestProp testProp;

@GetMapping("/test")
public String test() {
return JSONObject.toJSONString(testProp);
}
}

2、TestProp类(@ConfigurationProperties):

package com.saint.config;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* @Component注解,使得该类自动注入到Spring.
* 也可以按需在第一次使用TestProp的类上添加@EnableConfigurationProperties(TestProp.class)注解,将其注入。
* @author 周鑫(玖枭)
*/
//@Component
@ConfigurationProperties(prefix = "user")
@Data
@ToString
public class TestProp {

/**
* 姓名
*/
private String name;

/**
* 性别
*/
private Boolean sex;

/**
* 出生日期
*/
private Date birth;

/**
* 年龄
*/
private Integer age;

/**
* 地址
*/
private Address address;
/**
*
*/
private String[] interests;

/**
* 朋友
*/
private List<String> friends;

/**
* 技能分数
*/
private Map<String, Double> score;

/**
* 拥有的工具
*/
private Set<Double> tools;

/**
* 所有朋友的地址
*/
private Map<String, List<Address>> allFriendAddress;

}

3、application.yml文件:

user:
name: Saint
sex: true
birth: 2020/2/2 12:00:00 #格式必须为yyyy/M/d HH:mm:ss 或 yyyy/MM/dd
age: 18
address:
city: nanjing
street: shazhou
interests:
- football
- swimming
friends:
- Bob
- rupali
score: {math: 100, ehglish: 8}
tools: [12.3, 13.4, 14.5]
allFriendAddress:
bestFriend:
- {city: shanghai, street: nanjinglu}
- city: beijing
street: xierqi
commoneFriend:
- { city: hainan, street: dao }
- city: jiangsu
street:

4、两种注入TestProp类的方式样例

1)@Component + @ConfigurationProperties()

在需要使用到TestProp的地方直接使用@Autowired注入即可。

样例如下:

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_yaml_02


《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_spring boot_03

2)@EnableConfigurationProperties(xxx.class) + @ConfigurationProperties()

在需要使用到TestProp的地方(或者在一个@Configuration注解注释的配置类中),使用@EnableConfigurationProperties(xxx.class)让@ConfigurationProperties注解生效,@ConfigurationProperties注解会把properties或者yml配置文件转化为bean;再使用@Autowired注入TestProp即可。

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_java_04


《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_java_05


有强迫症的老哥可以使用下面方式移除报红,​​@Autowired(required = false)​​表示自动注入的时候Bean可以不存在:

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_spring boot_06

这种方式在Spring源码中被广泛使用:

比如:Spring MVC的配置类(WebMvcProperties)

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_spring_07


其在​​WebMvcAutoConfiguration​​​类的静态内部类​​WebMvcAutoConfigurationAdapter​​上被通过@Configuration + @EnableConfigurationProperties的方式被注入到Spring IOC容器中。

《SpringBoot系列一》:yaml配置文件各种数据类型使用姿势(含@EnableConfigurationProperties、@ConfigurationProperties)_yaml_08


举报

相关推荐

0 条评论