SpringBoot或SpringCloud获得yml参数的方法
如我的yml文件中有如下内容
myYml: test: phone: ${romdom.int[10,60]} name: ${romdom.value} age: ${romdom..int[10,60]}
那么我们可以通过如下方式获得test下面的内容
1,创建任意一个类,这个类必须有spring管理,即加入扫描
@Component @ConfigurationProperties(prefix = "myYml") public class MyYmlConfig { private Map<String, String> test = new HashMap<String, String>(); public Map<String, String> getTest() { return test; } public void setTest(Map<String, String> test) { this.test = test; } // String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要
上面注解中myYml表示了我们yml文件中,我们需要查询字段的一级节点名称
类里面的遍历test表示我们需要查询的二级节点
2,在需要使用变量的地方注入这个类即可,如下面完整的类
@RestController @RequestMapping("/activiti") public class TaskOperate { @Autowired private MyYmlConfig myYmlConfig; @RequestMapping("/test") public Test testTask() { //JSON.pmyYmlConfig.getTest(); Test test = JSON.parseObject(JSON.toJSONString(myYmlConfig.getTest()), new TypeReference<Test>(){}); return test; } }
如上所示,未如果有对应的bean,未甚至可以直接转换为一个bean
爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情