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

How to read property file values into set of Strings in Spring boot

我试过使用

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

但是当 white.listed.hotel.ids 为空时,也设置了一个带有空白值的尺寸。

white.listed.hotel.ids =

谁能帮我提供一个版本,如果在 属性 文件中指定,whiteListedHotelIds 可以包含任一值或没有空白案例的项目。

您可以调用自定义方法 (, itself inspired by ):

@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;
    }
}

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

通过构造函数注入 @Value(你总是应该这样做)并在那里完成你需要的所有 post 处理:

@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 复杂化。

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

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