什么是在Spring中将属性文件值转换为字符串集的有效方法

ank*_*pta 2 java spring properties-file java-8 spring-boot

我试过用

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

但是当white.listed.hotel.ids为空时,还设置了一个带空白值的大小.

white.listed.hotel.ids =

有人请帮我一个版本,其中whiteListedHotelIds可以包含属性文件中指定的值或没有空白案例的项目.

ale*_*xbt 5

你可以调用一个自定义方法(如其他答案所述,构建一个地图,本身的灵感来自@ FedericoPeraltaSchaffner的回答):

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在此方法中,您可以根据需要自由处理属性(例如,空时的特定逻辑).