SpringBoot之通过yaml绑定注入数据

依赖包:

        <!--配置文件注解提示包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

JavaBean:(此处使用lombok,可省略setter、getter等方法)

 1 package org.springboot.model;
 2 
 3 import lombok.Data;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.boot.context.properties.ConfigurationProperties;
 6 import org.springframework.stereotype.Component;
 7 
 8 import java.util.Date;
 9 import java.util.Map;
10 
11 /**
12  * @Description: 通过yaml绑定,注入数据的模型
13  **/
14 
15 @Data
16 @Component
17 @ConfigurationProperties(prefix = "teather")
18 public class Teather {
19     @Value("小红") //单个赋值,优先级低
20     private String name;
21 //    @Value("${teather.age}")  // 使用SpringEl读取配置文件中的值并注入
22     private String age;
23     private Date birthday;
24     private Boolean gender;
25     private String[] hobbies; //集合处理方式和数组相同
26     // {省:江苏,市:南京}
27     private Map<String, Object> location;
28 
29 }

application.yml

#  通过yaml绑定,注入数据
teather:
  name: Cate
  age: 29
  birthday: 1989/01/16
  gender: true
  hobbies: [唱歌,跳舞]
  location: {Province: "江苏",City: "南京"}

已缩进来区分同级,并且冒号后必须有空格。 

测试代码:

package org.springboot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.model.Teather;
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 DemoApplicationTests {
    @Autowired
    Teather teather;


    //通过yaml绑定,注入数据
    @Test
    public void testTeather() {
        System.out.println(teather);
    }


}

执行结果

Teather(name=Cate, age=29, birthday=Mon Jan 16 00:00:00 CST 1989, gender=true, hobbies=[唱歌, 跳舞], location={Province=江苏, City=南京})

此处绑定注入类型分为批量注入和单个注入,批量注入的优先级较高,两种方式的比较如下图: 

原文地址:https://www.cnblogs.com/gongxr/p/10234817.html