7 YAML与属性值注入与配置文件占位符

  • 全局配置文件定义为applicaton.yml时,内容遵循YAML语法

1 yml语法

1.1 基本语法
  server: port: 8080
  语句中包含两个空格,不能少

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

  server:
    servlet:
      session:
        cookie:
          path: /path
    port: 8081

  属性和值也是大小写敏感
1.2 值的写法
1.2.1 字面量:普通的值(数字,字符串,布尔)
k: v:字面直接来写;

字符串默认不用加上单引号或者双引号;
	""(双引号):不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
		eg:name: “spring \n boot”
 			输出:
 				spring 
 				boot
		
	''(单引号):会转义特殊字符,特殊字符最终只是一个普通的字符串数据
		eg:name: ‘spring \n boot’ 
			输出:
				spring \n boot
1.2.2 对象、Map(属性和值)(键值对):
k: v:在下一行来写对象的属性和值的关系;注意缩进
对象还是k: v的方式

picture:
    brand: 神舟
    price: 5000
    
行内写法:
	picture: {brand: 神舟,price: 5000}
1.2.3 数组(List、Set):
用- 值表示数组中的一个元素

picture:
 - 神舟
 - 美帝良心联想
 
行内写法
	picture: [神舟,美帝良心联想]

2 配置文件值注入

2.1 application.yml
person:
  lastName: gp6
  age: 22
  boss: false
  birth: 2018/11/16
  maps: {brand: 神舟,price: 5000}
  lists: [神舟,美帝良心联想]
  dog:
    name: 小白
    age: 15
2.2 实体类
  • Dog
package com.gp6.springboot07.bean;

public class Dog {

    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Dog{" +"name='" + name + '\'' +", age=" + age +'}';
    }

    get...
	set...
}

  • Person
package com.gp6.springboot07.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

/*
    将配置文件(application.yml)中配置的每一个属性的值,映射到这个组件中

    @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
    prefix = "person":配置文件中哪个下面的所有属性进行一一映射

    只有这个组件是容器中的组件(加入@Component),才能容器提供的@ConfigurationProperties功能

    @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值

*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    @Override
    public String toString() {
        return "Person{" + "lastName='" + lastName + '\'' + ", age=" + age + ", boss=" + boss + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists + ", dog=" + dog + '}';
    }
    
	get...
	set...

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
2.4 测试
package com.gp6.springboot07;

import com.gp6.springboot07.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * SpringBoot单元测试;
 *
 * 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestYml {
    @Autowired
    Person person;

    @Test
    public void test() {
        System.out.println(person);
    }
}

测试结果

3 使用application.properties

  • 将application.yml中person注释,在application.properties中添加
person.age=22
person.lastName=gp6
person.boss=false
person.birth=2018/11/16
person.maps.brade=神舟
person.maps.price=5000
person.lists=神舟,美帝良心联想
person.dog.name=小白
person.dog.age=15

4 使用@Value

  • 将application.yml和application.properties(除person.lastName=gp6)中person注释
4.1 实体类
package com.gp6.springboot07.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

@Component
public class PersonValue {
    /*
        xml配置方式:
            <bean class="Person">
                <property name="lastName" value="value"></property>
            <bean/>

        value有三种:
            1: 字面量:
                value="gp6"

            2: ${key}从配置文件中获取值
                @Value("${person.lastName}")

            3: #{SpEL}
     */
    @Value("${person.lastName}")
    private String lastName;
    @Value("#{22 + 2}")
    private Integer age;
    @Value("#{1 == 1}")
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    @Override
    public String toString() {
        return "PersonValue{" + "lastName='" + lastName + '\'' + ", age=" + age + ", boss=" + boss + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists + ", dog=" + dog + '}';
    }
    
	get...
	set...
4.2 测试
package com.gp6.springboot07;

import com.gp6.springboot07.bean.PersonProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestProperties {
    @Autowired
    PersonProperties personProperties;

    @Test
    public void test() {
        System.out.println(personProperties);
    }
}

测试结构

5 @Value和@ConfigurationProperties比较

5.1 注入方式
@Value:只能单个注入
		@Value("${person.lastName}")
		private String lastName;
		@Value("#{22 + 2}")
		private Integer age;
		
@ConfigurationProperties可以批量注入
5.2 绑定方式
@Value:严格匹配
		@Value("${person.lastName}")
		private String lastName;
		
		person.lastName=gp6
		
@ConfigurationProperties:松散绑定
		person.last-name=gp6
		和
		person.lastName=gp6  效果一致
5.3 SpEl
	@Value:支持
			@Value("#{22 + 2}")
			private Integer age;
			
	@ConfigurationProperties:不支持
5.4 hibernate-validator校验
	@Value:不支持
	
	@ConfigurationProperties:支持
			@Validated
			public class Person {
					@Email
					private String lastName;
					
					......
			}

校验结果

5.5 复杂类型封装
	@Value:支持
			@Value("${person.maps}")
			private Map<String, Object> maps;
			启动报错
			
	@ConfigurationProperties:支持
5.6 结论
	获取一下配置文件中的某项值,使用@Value;
	
	一个javaBean和配置文件进行映射,使用@ConfigurationProperties;

6 配置文件占位符

6.1 随机数
${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
6.2 占位符获取之前配置的值,如果没有可以是用:指定默认值
  • application.properties
# ${random.uuid}:随机uuid
person.last-name=gp6${random.uuid}

# ${random.int}: 随机int类型的数值
person.age=${random.int}

person.birth=2018/11/19
person.boss=true
person.maps.k1=神舟
person.maps.k2=联想
person.lists=火箭,雷霆,勇士

# ${person.last-name}:获取person.last-name定义的值
# 使用 : 定义默认值
person.dog.name=${person.last-name:gp6}的dog
person.dog.age=15 
  • 使用 TestYml测试
    运行结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值