注意:根据 Spring Boot 松散绑定,类的属性名称必须与外部属性的名称匹配
1 2 3 4 5 6 7 8 9
| 格式: user: user_name: 赵云 user: userName: 赵云 user: USERNAME: 赵云 user: user-name: 赵云
|
以上四种命名可以自动绑定bean属性(properties配置文件也可用该注解)
激活 @ConfigurationProperties
我们除了在实体类上标注注解@ConfigurationProperties,还需要让spring容器知道它的存在,以便将其加载到应用程序上下文中。
所以,我们可以通过添加 @Component 注解让 Component Scan 扫描到
${user.userName}只支持属性的调用,不支持运算
测试
yml配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| server: port: 8081
user: driver: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/javaweb_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai userName: root password: 111 girlFriend: {18: 范冰冰, 20: 迪丽热巴 } hobby: [打球, 听歌, 打游戏] address: id: 1 desc: ${user.userName}在柳州
|
Person实体类:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Component @ConfigurationProperties(prefix = "user") public class Person { private String driver; private String url; private String userName; private String password; private List<String> hobby; private Map<Integer, String> girlFriend; private Address address; get/set方法... }
|
Address实体类:
1 2 3 4 5 6 7
| public class Address { private Integer id; private String desc; get/set...方法
}
|
用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Controller public class BJController { @Autowired private Person person;
@RequestMapping("/test") @ResponseBody public Map<String, Object> test(){
Map<String, Object> map = new HashMap<>(); map.put("url", person.getUrl()); map.put("userName", person.getUserName()); map.put("password", person.getPassword()); map.put("className", person.getDriver()); map.put("GirlFriend", person.getGirlFriend()); map.put("hobby", person.getHobby()); map.put("id", person.getAddress().getId()); map.put("address", person.getAddress()); return map; } }
|
输出 JSON格式:
1
| {"password":"111","address":{"id":1,"desc":"root在柳州"},"className":"com.mysql.cj.jdbc.Driver","GirlFriend":{"18":"范冰冰","20":"迪丽热巴"},"id":1,"userName":"root","url":"jdbc:mysql://localhost:3306/javaweb_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai","hobby":["打球","听歌","打游戏"]}
|
总结
- @ConfigurationProperties 和 @value 有着相同的功能,但是 @ConfigurationProperties的写法更为方便
- @ConfigurationProperties 的 POJO类的命名比较严格,因为它必须和prefix的后缀名要一致, 不然值会绑定不上, 特殊的后缀名是“driver-class-name”这种带横杠的情况,在POJO里面的命名规则是 下划线转驼峰 就可以绑定成功,所以就是 “driverClassName”