码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot yaml 自定义配置 映射到 java POJO

时间:2019-03-26 12:02:49      阅读:512      评论:0      收藏:0      [点我收藏+]

标签:list   使用   依赖注入   pac   import   tps   nbsp   targe   spec   

 

 

只需要一个注解就ok: 

@ConfigurationProperties("user.other")

“user.other” 这个值匹配的是user下的other对象

 

 

yaml :

yaml 的语法:  https://yaml.org/spec/1.2/spec.html#directive//

user:
  user-name: addiction
  age: 19
  friends:
    - Smith
    - Shadow
    - Kathrin
  other:
    grand-test: test
    color: colorful
    price: $223
    test:
      -
        user-name: addiction
        age: 19
      -
        user-name: addiction
        age: 19
      -
        user-other: addiction
        age-other: 19
    other:
      test: "this is test"
      nums:
        - 1
        - 2
        - 65

 

UserProperty类: 

其中的属性名要和yml一一对应,  grandTest 在 yml 中对应的是 grand-test, 会自动转成驼峰

用 lombok 的 @Data  注解 生成getter/setter, 加上spring 的 @Component 方便 依赖注入

@Data
@Component
@ConfigurationProperties("user.other")
public class UserProperty {
    private String grandTest;
    private String color;
    private String price;

    private List<Map<String, Object>> test;

    private Other other; //POJO 类
}

 

 

Other 类

@Data
public class Other {

    private String test;

    private List<Integer> nums;
}

 

 

测试结果: 

 

技术图片

技术图片

 

测试基类

package com.example.demo;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest {
}

 

 

另外还可使用@Value注解修饰属性来获取yaml中的内容:

@Value("${user.other.color}")
private String color;

 

spring boot yaml 自定义配置 映射到 java POJO

标签:list   使用   依赖注入   pac   import   tps   nbsp   targe   spec   

原文地址:https://www.cnblogs.com/jxlsblog/p/10599181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!