1. 新建SpringBoot2工程。

2. 把application.properties改名为application.yaml, 并输入intVal和stringVal等配置
注意:配置冒号有要有空格。

2. 添加配置文件对应类
package cn.gongler.learn.springboot2.learn1;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix="gongler.learn1")
public class MyProperties {
int intVal = 123;
String stringVal = "defaultStr";
}
解释:
@ConfigurationProperties(prefix="gongler.learn1")指定了哪个类是配置文件对应类,以及配置文件中的统一前缀。
注意这个类不是Bean不是组件,只是表示映射关系。
3. 指定哪个配置文件映射类
@EnableConfigurationProperties(MyProperties.class)
@Configuration
public class MyConfiguration {
}
注意:必须同时与组件注解搭配,才能生效。推测是,枚举beans组件库。
4. 添加Controller类
@Component
@RestController
@RequestMapping("gongler")
public class Controller {
@Autowired MyProperties properties;
@GetMapping("learn1")
public MyProperties hello(){
return properties;//http://127.0.0.1:8080/gongler/learn1 返回:{"intVal":123,"stringVal":"defaultStr"}
}
}
利用@Autowired把组件注入properties
@RestController使得返回properties对象自动转换成json。
5. 测试

可以看到配置参数被成功载入。
未配置项会保留类的初始值。
多于的配置项不会报错。实际上一个配置文件可以对应多个映射类。不同模块各取所需。
@EnableConfigurationProperties(class)可以有条件产生Bean;@Component是无条件产生bean,所以不可以同时作用。这就是通常为什么SpringBoot中@ConfigurationProperties不与@Component一起约束同一个类的原因。
其他:
使用org.yaml.snakeyaml.scanner解析yaml配置文件。
本文详细介绍了如何在SpringBoot2中将application.properties更改为yaml格式,并配置及使用@ConfigurationProperties。通过创建配置文件对应类,设置配置前缀,然后在配置类中启用配置属性,最终在Controller中注入并使用这些配置。测试显示配置参数已成功加载,未配置项保留默认值,多余的配置项不会引发错误。此外,讨论了@ConfigurationProperties与@Component注解的区别。
1189

被折叠的 条评论
为什么被折叠?



