Search code examples
spring-integrationspring-el

headers - spel to split the string


I have to split the string present in the headers.

<int:header name="plans-array" expression="headers['plans'].split(',')"/>

How to make this String array into List like the below one which converts the list automatically.

 @Value("#{'${plans}'.split(',')}") 
 private List<String> myList;

I tried like below but is not working correctly.

<int:header name="plans-list" expression="T(java.util.Arrays).asList(headers['plans'].split(','))"/>

integration xml

<int:channel id="splitChannel"/>
<int:header-enricher input-channel="splitChannel">
    <int:header name="isPlanExist" expression="T(java.util.Arrays).asList((headers['plans'].split(','))).contains('plan1')"/>
</int:header-enricher>

JUnit

    @Autowired
    @Qualifier("splitChannel")
    private MessageChannel splitChannel;

    @Test
    public void testSplit() {

String somePayload = "somePayload";
Message<String> stringPayload = MessageBuilder.withPayload(somePayload)
    .setHeader("plans", "plan1,plan2")
    .build();

MessagingTemplate template = new MessagingTemplate();
Assert.assertEquals(true, template.sendAndReceive(this.splitChannel, stringPayload).getHeaders().get("isPlanExist"));

Solution

  • Good, now I see your problem.

    You have code like T(java.util.Arrays).asList((headers['plans'].split(',')))

    In Java it works fine because compiler treat one argument with array type as a varargs.

    Here we have a SpEL, which in most case is based on the reflection method invocation. So, there is no compiler optimization and we end up with the fact of List<String[]> with one element, not like you expect List<String> with two elements.

    I wouldn't say that it is a SpEL problem. That is how Java reflection works here.

    To fix your problem you should consider to use some other array -> list utility to bypass varargs issue, e.g.:

    T(org.springframework.util.CollectionUtils).arrayToList(headers['plans'].split(',')).contains('plan1')