spring-integrationspring-elspelevaluationexception

How to use SPEL to reference attribute of parameter in @GatewayHeader


This should be a simple question, but I cannot find the proper doc online. I want to do this:

@MessagingGateway(name = "redemptionGateway", defaultRequestChannel = Channels.GATEWAY_OUTPUT, defaultHeaders = @GatewayHeader(name = "orderId", expression = "#redemption.orderId"))
public interface RedemptionGateway {
    void create(TrivialRedemption redemption);
}

I am obviously using the wrong statement to reference the orderId member of redemption:

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'orderId' cannot be found on null

Solution

  • OK. Look

    @GatewayHeader(name = "orderId", expression = "#redemption.orderId")
    

    This SpEL is evaluated at runtime against actual arguments to build MessageHeaders for target Message to send.

    And that is how it looks:

    private StandardEvaluationContext createMethodInvocationEvaluationContext(Object[] arguments) {
        StandardEvaluationContext context = ExpressionUtils.createStandardEvaluationContext(this.beanFactory);
        context.setVariable("args", arguments);
    
        context.setVariable("gatewayMethod", this.method);
        return context;
    }
    

    So, EvaluationContext is enriched with two variables args and gatewayMethod.

    As you see, there is no any arguments population by their name. Will that work anyway for all the JVMs?

    You can achieve your goal using parameter index from the args:

    expression = "#args[0].orderId"