【问题标题】:How to read property file values into set of Strings in Spring boot如何在 Spring Boot 中将属性文件值读入字符串集
【发布时间】:2017-03-05 09:12:45
【问题描述】:

我尝试过使用

@Value("#{'${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;

但是当 white.listed.hotel.ids 为空时,也设置了一种尺寸和空白值。

white.listed.hotel.ids =

有人可以帮我提供一个版本,其中 whiteListedHotelIds 可以包含任何值(如果在属性文件中指定)或没有用于空白大小写的项目。

【问题讨论】:

  • 您的意思是在 whiteListedHotelIds 为空的情况下指定默认值吗?
  • @Georgesvanhoutte van houtte:我只是希望集合为空,以防 whiteListedHotelIds 为空。

标签: java spring spring-boot java-8 properties-file


【解决方案1】:

您可以调用自定义方法(as described in this other answer to build a map,其灵感来自@FedericoPeraltaSchaffner's answer):

@Value("#{PropertySplitter.toSet('${white.listed.hotel.ids}')}")
private Set<String> fareAlertwhiteListedHotelIds;

...

@Component("PropertySplitter")
public class PropertySplitter {
    public Set<String> toSet(String property) {
        Set<String> set = new HashSet<String>();

        //not sure if you should trim() or not, you decide.
        if(!property.trim().isEmpty()){
            Collections.addAll(set, property.split(","));
        }

        return set;
    }
}

在此方法中,您可以随意处理属性(例如为空时的特定逻辑)。

【讨论】:

  • Collections.addAll(set, property.split(",")); 跳过中间的List 步骤。
  • 谢谢@Holger!我已将 Arrays.asList(...) 替换为您的建议!
【解决方案2】:

您也可以使用spring表达式语言进行验证,如果提供的字符串为空,则返回空数组或将输入字符串拆分为数组。从 jdk-11 你可以直接使用isBlank

@Value("#{'${white.listed.hotel.ids}'.trim().isEmpty() ? new String[] {} : '${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;

【讨论】:

    【解决方案3】:

    通过构造函数注入@Value(正如你一直应该做的那样)并在那里进行你需要的所有后处理:

    @Component
    class Foo {
        private final List<String> bar;
    
        public Foo(@Value("${foo.bar}") List<String> bar) {
            this.bar = bar.stream()
                          .filter(s -> !"".equals(s))
                          .collect(Collectors.toList());
        }
    }
    

    SPEL 没有必要让事情复杂化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 2016-04-29
      • 2018-10-16
      • 2018-09-28
      • 2019-01-11
      相关资源
      最近更新 更多