SpringBoot基础 之YAML @ConfigurationProperties @Value @PropertySource 配置文件相关

目录

一、YAML语法

二、配置文件注入

2.1 @ConfigurationProperties 

2.2 @Value

【总结如下】

2.3 @PropertySource 加载指定的配置文件

2.4 @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效


一、YAML语法

1、基本语法

k:(空格)v:表示一对键值对,空格必须有

以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的。

server:
  port: 8081

xiaozheng:
  name: xiaozheng

属性和值也是大小写敏感的

2、值的写法

2.1 普通的值(数字、字符串、布尔、时间...)

格式为: k: v

字符串默认可以不加上:双引号或者单引号

若加上双引号"",则不会转义字符串里面的特殊字符;字符串本身想表达的意思

若加上单引号'',则会转义字符串里面的特殊字符,转化为一个普通的字符串

若不加双引号和单引号,效果跟单引号一样。

// 在application.yml中配置person属性
person:
  name: 小\t郑
  age: 18
  first-name: "小\t郑"
  last_name: '小\t郑'


// 然后新建Person01类,使用@ConfigurationProperties注解注入
@Component
@ConfigurationProperties(prefix = "person")
public class Person01 {
    private String name;
    private Integer age;
    private String lastName;
    private String firstName;
    private boolean flag;
    private Date birth;
    private Map<String, Object> maps;
    private List<String> lists;
    public String getName() {
        return name;
    }
    .... // get and set and toString method忽略
}

// 注意这里需要写入:Component注解,启动的时候,交给spring管理

// 测试用例
@SpringBootTest
@RunWith(SpringRunner.class)
class SpringBoot02ConfigApplicationTests {
   
    @Autowired
    private Person01 person01;
    @Test
    void testPerson01() {
        System.out.println(person01.toString());
    }
}

结果打印输出:

【学习建议】建议大家建个spring-boot项目,按照上面的语法操作一下。这样会印象深刻。

2.2 对象、Map(属性和值)(键值对):

k: v :在下一行来写对象的属性和值的关系;注意缩进
对象还是 k: v 的方式
maps2: 
    key1: value1
    key2: value2
    key3: value3

行内写法:

maps: {key1: value1, key2: value2, key3: value3}

2.3 数组(List、Set)

用 - 表示一个值

lists: [a, b, c]

行内写法

lists2:
    - a
    - b
    - c

打印输出

二、配置文件注入

2.1 @ConfigurationProperties 

prefix = "xxx" :配置文件中哪个下面的所有属性进行一一映射

<!‐‐导入配置文件处理器,配置文件进行绑定就会有提示‐‐>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
</dependency>

在Person01中,使用

@Component
@ConfigurationProperties(prefix = "person")
public class Person01 {
    private String name;
    private Integer age;
    private String lastName;
    private String firstName;
    private boolean flag;
    private Date birth;
    private Map<String, Object> maps;
    private List<String> lists;
    public String getName() {
        return name;
    }
    .................
}

这样就可以将application.yml或application.properties的配置信息注入到改bean中

【注意:】默认情况下,加载的是主配置文件信息

2.2 @Value

既然说到了,配置文件值注入,不得不提Spring的一个注解@Value

两者对比一下:

理解如下:

1)松散绑定

表示驼峰式、下划线(_)、短横线(-)

标准方式
person.firstName

方式一
大写用-
person.first-name

方式二
大写用_
person.first_name

三种方式,都可以使用

上述的三种写法,都可以将配置属性注入到
firstName属性值中

但是对于@Value来说,每一个值去绑定,就要求你跟配置文件的key一模一样,才能注入。

2)SpEl语法

关于SpEl语法的理解,查看这篇

https://www.sohu.com/a/345723961_120325051

@Component
//@ConfigurationProperties(prefix = "person")
public class Person01 {
    @Value("#{'${xiaozheng.name}'.length() > 5 ? 'aaa' : 'bbb'}")
    private String name;


}

大白话理解:SPEL:Spring Expression Language 能够获取到配置文件的值后进行各种表达式操作

3)JSR303数据校验

推荐这篇文件:

https://www.sohu.com/a/345723961_120325051

用法:

// 1、在需要校验的Bean上使用 @Validated
// 2、然后在具体的字段上,使用各种校验注解

4)复杂数据类型

【总结如下】

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfifigurationProperties;
 

2.3 @PropertySource 加载指定的配置文件

      value: 通过 value 属性让它去加载指定路径配置文件
 

      我们了解完 @ConfigurationProperties 注解的使用,知道了它可以将 application.yml 或 application.properties 主配置文件中的属性值与 Java Bean 对应属性进行注入。

      此时就引出另一个问题,如果所有属性值都配置在 主配置文件 中,主配置文件就会越来越庞大,这显然是不可以的。此时我们可以使用 Spring 为我们提供的 @PropertySource 注解,去加载指定的配置文件,然后结合 @ConfigurationProperties 注解,便能够实现指定配置文件与 Java Bean 的注入操作。

 

@PropertySource(value = "classpath:person.properties")

【遇到的坑】

1、classpath:后面不能带有空格,带空格的话回去加载:(空格)person.properties文件,会报文件找不到错误

2、PropertySource默认情况下仅仅支持加载外部的、后缀为:properties配置文件,不支持yml、yaml文件。

指定factory

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        Resource resourceResource = resource.getResource();
        if (!resourceResource.exists()) {
            return new PropertiesPropertySource(null, new Properties());
        } else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
            List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
            return sources.get(0);
        }
        return super.createPropertySource(name, resource);
    }
}

然后使用@PropertySource注解时指定,factory

@PropertySource(factory = YamlAndPropertySourceFactory.class, value = {"classpath:person.yml"})

这样就可以支持注入yml文件了。

第一次学习时,在这里卡了很多。

2.4 @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效

SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件,也不能识别
想让Spring的配置文件生效,加载进来,使用该注解
@ImportResource(locations = {"classpath:beans.xml"}) 
导入Spring的配置文件让其生效

【个人建议】SpringBoot推荐给容器添加组件的方式:推荐使用注解的方式。

因此,我个人是不大推荐使用 该注解的。

不详细展开讲解

 
 
 
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值