spring boot yaml 自定义配置 映射到 java POJO
2024-09-05 11:06:17
只需要一个注解就ok:
@ConfigurationProperties("user.other")
“user.other” 这个值匹配的是user下的other对象
yaml :
yaml 的语法: https://yaml.org/spec/1.2/spec.html#directive//
user:
user-name: addiction
age:
friends:
- Smith
- Shadow
- Kathrin
other:
grand-test: test
color: colorful
price: '$223'
test:
-
user-name: addiction
age:
-
user-name: addiction
age:
-
user-other: addiction
age-other:
other:
test: "this is test"
nums:
-
-
-
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;
最新文章
- netsh端口转发
- JavaScript笔记基础篇(一)
- Linux内核如何装载和启动一个可执行程序
- BW CUBE 数据的聚集和压缩
- Object C语法学习
- 2016/9/7 jdbc.properties配置数据库相关
- ASP.NET的GET和POST方式的区别归纳总结
- EventBus 事件总线 案例
- 【LeetCode练习题】Evaluate Reverse Polish Notation
- poj1580---欧几里得算法(辗转相除法)
- for(;;)和 while(1) 有什么区别吗?for()和while()的使用情景。
- (转)Python-正则表达式
- 基于jq的表单填充
- JS异常
- 参数FAST_START_MTTR_TARGET的理解
- 48- java Arrays.sort和collections.sort()再次总结
- Guidelines for Writing a Good NIPS Paper
- DevExpress WinForms使用教程:WinForms Fluent Design和Acrylic Effects
- Java NIO Path
- SQL语句之奇形怪状的冷门函数
热门文章
- IDEA导入HttpServlet包
- JavaScript进阶 - 第2章 你要懂的规则(JS基础语法)
- 目前最全的浏览器/CSS选择器兼容性总结(2009-8-10更新)
- GUI的最终选择 Tkinter(七):菜单Menu组件、Menubutton组件、OptionMenu组件
- ASP .NET Core 2.1 HTTP Error 502.5 – Process Failure
- Announcing .NET Core 2.1
- D. Array Division
- Adobe CC Family (CC 2015) 大师版
- webpack.config.js====插件purifycss-webpack,提炼css文件
- String类、StringBuilder类、StringBuffer类