Spring yml转java_spring boot yaml 自定义配置 映射到 java POJO

只需要一个注解就ok:

@ConfigurationProperties("user.other")

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

yaml :

user:

user-name: addiction

age:19friends:-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: 19other:

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 classUserProperty {privateString grandTest;privateString color;privateString price;private List>test;privateOther other; //POJO 类

}

Other 类

@Datapublic classOther {privateString test;private Listnums;

}

测试结果:

20190326120249420233.png

20190326120249759113.png

测试基类

packagecom.example.demo;importorg.junit.runner.RunWith;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)

@SpringBootTestpublic classBaseTest {

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值