本文共 3256 字,大约阅读时间需要 10 分钟。
1> 引入 spring-boot-configuration-processor 库
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> 2> 在 application.yml 中要获取的数据
simple-prop: simplePropValue 注 : 1> 注意命名规则,根节点不能采用驼峰命名法,否则将会导致识别失败这是在 2.0.1.RELEASE 出现的问题,最好全部小写,剩余的其他字段可以采用驼峰命名法,可以使用 - 方式来修改 3> 使用 @ConfigurationProperties 将数据绑定到对象上有两种方式
方式1> 在方法上引入 @ConfigurationProperties 注解
private String simpleProp; private String[] arrayProps; private List<Map<String, String>> listProp1 = new ArrayList<>(); private List<String> listProp2 = new ArrayList<>(); private Map<String, String> mapProps = new HashMap<>(); public String getSimpleProp() { * String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要 public void setSimpleProp(String simpleProp) { this.simpleProp = simpleProp; public String[] getArrayProps() { public void setArrayProps(String[] arrayProps) { this.arrayProps = arrayProps; public List<Map<String, String>> getListProp1() { public void setListProp1(List<Map<String, String>> listProp1) { this.listProp1 = listProp1; public List<String> getListProp2() { public void setListProp2(List<String> listProp2) { this.listProp2 = listProp2; public Map<String, String> getMapProps() { public void setMapProps(Map<String, String> mapProps) { this.mapProps = mapProps; @ConfigurationProperties(prefix = "myprops") public MyProps myProps() { 方式2> 在类上使用 @ConfigurationProperties 注解
@ConfigurationProperties(prefix = "myprops") private String simpleProp; private String[] arrayProps; private List<Map<String, String>> listProp1 = new ArrayList<>(); private List<String> listProp2 = new ArrayList<>(); private Map<String, String> mapProps = new HashMap<>(); public String getSimpleProp() { * String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要 public void setSimpleProp(String simpleProp) { this.simpleProp = simpleProp; public String[] getArrayProps() { public void setArrayProps(String[] arrayProps) { this.arrayProps = arrayProps; public List<Map<String, String>> getListProp1() { public void setListProp1(List<Map<String, String>> listProp1) { this.listProp1 = listProp1; public List<String> getListProp2() { public void setListProp2(List<String> listProp2) { this.listProp2 = listProp2; public Map<String, String> getMapProps() { public void setMapProps(Map<String, String> mapProps) { this.mapProps = mapProps; public void propsTest() { System.out.println("simpleProp: " + myProps.getSimpleProp()); 转载地址:http://zogab.baihongyu.com/