4

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.

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
ankita gupta
  • 193
  • 1
  • 3
  • 12

3 Answers3

5

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).

Community
  • 1
  • 1
alexbt
  • 16,415
  • 6
  • 78
  • 87
1

You can use the spring expression language for validation as well, if the provided string is empty then return empty array or split input string into array. From jdk-11 you can use isBlank directly

@Value("#{'${white.listed.hotel.ids}'.trim().isEmpty() ? new String[] {} : '${white.listed.hotel.ids}'.split(',')}")
private Set<String> fareAlertwhiteListedHotelIds;
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

Inject @Value through constructor (as you always should) and do all post-processing you need there:

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

There is no need to complicate things with SPEL.

Maciej Walkowiak
  • 12,372
  • 59
  • 63