ankita gupta ankita gupta - 1 month ago 6
Java Question

What is the Efficient way to get Property file values into set of Strings in Spring

I have tried using

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


but When white.listed.hotel.ids is empty then also set has one size with blank value.


white.listed.hotel.ids =


Can someone pls help me with a version in which whiteListedHotelIds can contain either values if specified in property file or has no item for blank case.

Answer

You can call a custom method (as described in this other answer to build a map, itself inspired by @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;
    }
}

In this method, you are free to handle the property as you wish (for instance a particular logic when empty).

Comments