当前位置: 代码迷 >> 综合 >> 面试: Spring Boot YAML,第二篇
  详细解决方案

面试: Spring Boot YAML,第二篇

热度:113   发布时间:2023-09-30 03:29:37.0

什么是YAML

  1. Yet A Mark Language 一种标记语言
  2. YAML Are not Mark Language YAML不是标记语言
  3. YAML是一种以数据为中心的标记语言,语法格式简洁,节省存储空间。
  4. 如果开发人员需要修改Spring Boot依赖框架的默认配置,可以在resources文件夹下创建application.propertities和application.yml文件。并在其中添加相应配置,Spring Boot将会读取用户配置去取代默认配置。

YAML的语法

  1. 表示字面量(键值对):
key: value
age: 19
  1. 对象:
Michael:name: "Michael"age: 10Michael: {
    name: "Michael", age: 19}

双引号会转义字符,单引号不会

  1. Map:
map: {
    key1: value1, key2: value2}
  1. List 和 set:
animals:- "dog"- "cat"- "bird"animals: ["dog", "cat", "bird"]
  1. 组合语法:
Michael:pet: ["dog", "cat"]age: 19name: "Michael"

如何 把YAML文件中的数据注入到Bean中

  1. 在application.yml添加配置
person: name: "Michael"age: 18map: {
    k1: v1, k2: v2}pets: ["p1", "p2"]
  1. 在主程序类同级包内创建同名Bean类,并注解@Component, @ConfigurationProperties(perfix = “person”):
    如何要把yml文件中的数据配置注入到类中,该类必须为一个组件。也就是说,该类必须被注入到容器中。@ConfigurationProperties的属性prefix的值需要和配置名称对应。
import java.util.List;
import java.util.Map;@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;private Integer age;private Map<String, String> map;private List<String> pets;@Overridepublic String toString() {
    return "Person{" +"name='" + name + '\'' +", age=" + age +", map=" + map +", pets=" + pets +'}';}
}

使用Spring注解@Value单独获取配置文件中的数据

@Value支持SpEL(Spring Expression Language)

	@Value("${person.name}")//获取配置文件中属性的值private String name;@Value("false")//类型判断private boolean married;@Value("#{1 * 2}")//计算表达式private Integer age;

@ConfigurationProperties支持Relaxed binding(松散绑定)

面试: Spring Boot YAML,第二篇

ConfigurationProperties支持属性验证

Spring Boot will attempt to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. Simply ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields.

In order to validate values of nested properties, you must annotate the associated field as @Valid to trigger its validation. For example, building upon the above FooProperties example:

@ConfigurationProperties(prefix="connection")
@Validated
public class FooProperties {
    @NotNullprivate InetAddress remoteAddress;@Validprivate final Security security = new Security();// ... getters and setterspublic static class Security {
    @NotEmptypublic String username;// ... getters and setters}}

@ConfigurationProperties 比较 @Value

面试: Spring Boot YAML,第二篇
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value。
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties。

额外知识点

根据官方表述:
“Any YAML content is ultimately transformed to properties. That process may be counter intuitive when overriding “list” properties via a profile.”

如果application.properties的数据被Spring Boot解析后出现乱码,去IDEA-》setting-》file encoding了里面修改文件编码格式。

  相关解决方案