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

 

 

只需要一个注解就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;

 

转载于:https://www.cnblogs.com/jxlsblog/p/10599181.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值