broken98
broken98

Reputation: 43

SPEL - Split and trim, de-limited values

I am trying to split String values based on de-limiter and trim them before putting them in a list.

I am able to split the values, could you please suggest how can be trim the list.

@Value("#{'${string-values}'.split(',')}")
private List<String> textList;

The problem it seems is, Split returns a list and I need to invoke trim() before storing them in the variable.

Upvotes: 0

Views: 3354

Answers (4)

pravat
pravat

Reputation: 475

Check Java - Split and trim in one shot

@Value("#{'${string-values}'.split('\\s*,\\s*')}")
private List<String> textList;

Upvotes: 3

Gary Russell
Gary Russell

Reputation: 174634

Since you are using Spring Boot, use:

@Component
@ConfigurationProperties(prefix = "foo.bar")
public class MyConfig {

    private List<String> list = new ArrayList<>();

    public List<String> getList() {
        return this.list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}
foo.bar.list=      a   ,   b,    c

The list entries are trimmed.

Upvotes: 0

Hemant
Hemant

Reputation: 1438

Better to provide no space between values in properties file.

To put a check in code it can be done in this way.

private List<String> textList;

public YourController(@Value("${string-values}") String propertyFromFile) {
        this.textList = new ArrayList<>(); 
        Arrays.asList(propertyFromFile.split(",")).forEach(b-> this.textList.add(b.trim()));        
}

Upvotes: 1

Nithin
Nithin

Reputation: 703

I think it may be better to use @Configuration and then process that instead of doing like this, however you can add a new annotation on top of value annotation and use that annotation to process the list. For example

@Target(value = {ElementType.TYPE})
@Value
public @interface Trim {
 //Override the method you want to override
}

Public TrimPricessor {

//Implement the annotation method here
}

Upvotes: 0

Related Questions