依赖包:
<!--配置文件注解提示包--> <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 * @Auther:GongXingRui 13 * @Date:2019/1/7 14 * @Description: 通过yaml绑定,注入数据的模型 15 **/ 16 17 @Data 18 @Component 19 @ConfigurationProperties(prefix = "teather") 20 public class Teather { 21 @Value("小红") //单个赋值,优先级低 22 private String name; 23 private String age; 24 private Date birthday; 25 private Boolean gender; 26 private String[] hobbies; //集合处理方式和数组相同 27 // {省:江苏,市:南京} 28 private Map<String, Object> location; 29 30 }
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