spring boot 读取配置文件(application.yml)中的属性值

红太狼 2022-06-05 12:28 261阅读 0赞

在spring boot中,简单几步,读取配置文件(application.yml)中各种不同类型的属性值:

1、引入依赖:

[html] view plain copy

  1. <**dependency**>
  2. <**groupId**>org.springframework.boot</**groupId**>
  3. <**artifactId**>spring-boot-configuration-processor</**artifactId**>
  4. <**optional**>true</**optional**>
  5. </**dependency**>

2、配置文件(application.yml)中配置各个属性的值:

[plain] view plain copy

  1. myProps: #自定义的属性和值
  2. simpleProp: simplePropValue
  3. arrayProps: 1,2,3,4,5
  4. listProp1:
    • name: abc
  5. value: abcValue
    • name: efg
  6. value: efgValue
  7. listProp2:
    • config2Value1
    • config2Vavlue2
  8. mapProps:
  9. key1: value1
  10. key2: value2

3、创建一个bean来接收配置信息:

[java] view plain copy

  1. @Component
  2. @ConfigurationProperties(prefix=”myProps”) //接收application.yml中的myProps下面的属性
  3. public class MyProps {
  4. private String simpleProp;
  5. private String[] arrayProps;
  6. private List> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
  7. private List listProp2 = new ArrayList<>(); //接收prop2里面的属性值
  8. private Map mapProps = new HashMap<>(); //接收prop1里面的属性值
  9. public String getSimpleProp() {
  10. return simpleProp;
  11. }
  12. //String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要
  13. public void setSimpleProp(String simpleProp) {
  14. this.simpleProp = simpleProp;
  15. }
  16. public List> getListProp1() {
  17. return listProp1;
  18. }
  19. public List getListProp2() {
  20. return listProp2;
  21. }
  22. public String[] getArrayProps() {
  23. return arrayProps;
  24. }
  25. public void setArrayProps(String[] arrayProps) {
  26. this.arrayProps = arrayProps;
  27. }
  28. public Map getMapProps() {
  29. return mapProps;
  30. }
  31. public void setMapProps(Map mapProps) {
  32. this.mapProps = mapProps;
  33. }
  34. }

启动后,这个bean里面的属性就会自动接收配置的值了。

4、单元测试用例:

[java] view plain copy

  1. @Autowired
  2. private MyProps myProps;
  3. @Test
  4. public void propsTest() throws JsonProcessingException {
  5. System.out.println(“simpleProp: “ + myProps.getSimpleProp());
  6. System.out.println(“arrayProps: “ + objectMapper.writeValueAsString(myProps.getArrayProps()));
  7. System.out.println(“listProp1: “ + objectMapper.writeValueAsString(myProps.getListProp1()));
  8. System.out.println(“listProp2: “ + objectMapper.writeValueAsString(myProps.getListProp2()));
  9. System.out.println(“mapProps: “ + objectMapper.writeValueAsString(myProps.getMapProps()));
  10. }

测试结果:

[plain] view plain copy

  1. simpleProp: simplePropValue
  2. arrayProps: [“1”,”2”,”3”,”4”,”5”]
  3. listProp1: [{“name”:”abc”,”value”:”abcValue”},{“name”:”efg”,”value”:”efgValue”}]
  4. listProp2: [“config2Value1”,”config2Vavlue2”]
  5. mapProps: {“key1”:”value1”,”key2”:”value2”}

源代码参考:https://github.com/xujijun/my-spring-boot

发表评论

表情:
评论列表 (有 0 条评论,261人围观)

还没有评论,来说两句吧...

相关阅读