注解@ConfigurationProperties使用方法 (2)

注解@ConfigurationProperties使用方法

以上就完成了多个数据源的配置,为读写分离做了铺垫

作用于Class类及其用法 配置文件内容 spring.datasource.url=jdbc:mysql://127.0.0.1:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource java代码 @ConfigurationProperties(prefix = "spring.datasource") @Component public class DatasourcePro { private String url; private String username; private String password; // 配置文件中是driver-class-name, 转驼峰命名便可以绑定成 private String driverClassName; private String type; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getType() { return type; } public void setType(String type) { this.type = type; } } 用法 @Controller @RequestMapping(value = "/config") public class ConfigurationPropertiesController { @Autowired private DatasourcePro datasourcePro; @RequestMapping("/test") @ResponseBody public Map<String, Object> test(){ Map<String, Object> map = new HashMap<>(); map.put("url", datasourcePro.getUrl()); map.put("userName", datasourcePro.getUsername()); map.put("password", datasourcePro.getPassword()); map.put("className", datasourcePro.getDriverClassName()); map.put("type", datasourcePro.getType()); return map; } } 总结

@ConfigurationProperties 和 @value 有着相同的功能,但是 @ConfigurationProperties的写法更为方便

@ConfigurationProperties 的 POJO类的命名比较严格,因为它必须和prefix的后缀名要一致, 不然值会绑定不上, 特殊的后缀名是“driver-class-name”这种带横杠的情况,在POJO里面的命名规则是 下划线转驼峰 就可以绑定成功,所以就是 “driverClassName”

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwgzgd.html