Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Spring boot中将属性文件值读入字符串集_Java_Spring_Spring Boot_Java 8_Properties File - Fatal编程技术网

Java 如何在Spring boot中将属性文件值读入字符串集

Java 如何在Spring boot中将属性文件值读入字符串集,java,spring,spring-boot,java-8,properties-file,Java,Spring,Spring Boot,Java 8,Properties File,我试过使用 @Value("#{'${white.listed.hotel.ids}'.split(',')}") private Set<String> fareAlertwhiteListedHotelIds; @Value(“#{${white.listed.hotel.ids}.split(',')}”) 私人设置票价;白名单酒店; 但当white.listed.hotel.ids为空时,set也有一个值为空的大小 white.list.hotel.ids= 有人能帮我提

我试过使用

@Value("#{'${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;
@Value(“#{${white.listed.hotel.ids}.split(',')}”)
私人设置票价;白名单酒店;
但当white.listed.hotel.ids为空时,set也有一个值为空的大小

white.list.hotel.ids=


有人能帮我提供一个版本,其中whiteListedHotelIds可以包含属性文件中指定的值,或者没有用于空格的项。

您可以调用自定义方法(,其本身受以下启发):

@Value(“{PropertySplitter.toSet('${white.listed.hotel.ids}'))
私人设置票价;白名单酒店;
...
@组件(“PropertySplitter”)
公共类属性拆分器{
公共集合到集合(字符串属性){
Set=newhashset();
//不确定是否应该修剪(),由您决定。
如果(!property.trim().isEmpty()){
Collections.addAll(set,property.split(“,”);
}
返回集;
}
}

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

通过构造函数注入
@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());
    }
}
@组件
福班{
私人最终列表栏;
公共Foo(@Value(${Foo.bar}”)列表栏){
this.bar=bar.stream()
.filter(s->!“”.equals)
.collect(Collectors.toList());
}
}

没有必要使SPEL复杂化。

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

@Value("#{'${white.listed.hotel.ids}'.trim().isEmpty() ? new String[] {} : '${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;
@Value(“#{${white.listed.hotel.ids}.trim().isEmpty()?新字符串[]{}:'${white.listed.hotel.ids}.split(',')}”)
私人设置票价;白名单酒店;

您的意思是在whiteListedHotelIds为空的情况下指定默认值吗?可能重复@Georgesvanhoutte van houtte:我只是希望在whiteListedHotelIds为空的情况下集合为空。或者
Collections.addAll(set,property.split(“,”)跳过中间
列表
步骤。谢谢@Holger!我已经用你的建议替换了array.asList(…)!
@Value("#{'${white.listed.hotel.ids}'.trim().isEmpty() ? new String[] {} : '${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;