【问题标题】:Spring Boot: Read list of values from properties fileSpring Boot:从属性文件中读取值列表
【发布时间】:2020-07-01 17:10:46
【问题描述】:

我的属性文件包含以下值列表

prop.myVariable=v1,v2,v3

我尝试使用 spring boot 读取它们,如下所示:

@Value("#{'${prop.myVariable}'.split(',')}")
public static List<String> allowList;

当我尝试执行它时,它无法读取并获取 java.lang.NullPointerException

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    静态成员在加载属性之前被初始化。要解决此问题,请使用 setter 注入:

    public static List<String> allowList;
    
    @Value("#{'${prop.myVariable}'.split(',')}")
    public void setAllowList(List<String> list) {
        allowList = list;
    }
    

    【讨论】:

      【解决方案2】:

      正如我所见,您正在使用以下代码,为什么还要将属性保存到“列表”中

      List<String> allowList;
      @Value("#{'${prop.myVariable}'.split(',')}") 
      public List<String> setAllowList(List<String> list) { 
        this.list= list;
       } 
      String Chars = myProperties.getConfigValue("prop.myVariable"); 
      List<String> allowedCharacteristics = setCharacteristics(Chars); 
      

      您必须将属性存储到“允许列表”,使用下面的代码

      @Value("#{'${prop.myVariable}'.split(',')}")
      public void setAllowList(List<String> list) {
          allowList = list;
      }
      

      如果您必须专门使用“getConfigValue()”,请关注此线程 -> How to access a value defined in the application.properties file in Spring Boot

      【讨论】:

        【解决方案3】:

        我最终这样做了:

        @Value("#{'${prop.myVariable}'.split(',')}")
        private List<String> allowedCharacteristics;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-02-03
          • 2016-04-29
          • 1970-01-01
          • 2018-10-27
          • 2018-06-24
          • 2019-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多