Accessing mule flow variables from Java components

In one of the earlier steps of a mule flow, I extracted some data from the payload, and stored them in flow variables. This was done to save information like the database primary key which I would need to update the status buffer later, before transforming the payload to the required response message.

<flow name="someflow">
  <inbound-endpoint ref="jdbcEndpoint" doc:name="Generic" />
  <set-variable variableName="requestId" value="#[message.payload.requestId]"/>

Getting to these flow variables from within a Java component turned out to be a lot harder I had anticipated.

My first attempt was to use the @Mule annotation. I annotated my Java method as follows

    public void process(@Payload AmazingFilePayload payload,  
                        @Mule("flowVars['requestId']") Integer requestId) {
        // do stuff

The MEL was valid because I could access the flow variable within the mule flow with

<logger level="DEBUG" message="#[flowVars['requestId']]"/>

However, the above Java gave a StringIndexOutOfBoundsException with the message String index out of range: -1. Looking through the documentation, I couldn’t see how you access flow variables at all with Java annotations.

In the end, I resorted to implementing the Callable interface. It seemed an unsatisfactory work around to me, because

  1. the Java component was no longer a POJO
  2. I needed a different class for each update method, instead of writing a single class with many related methods
public class UpdateBuffer implements Callable {
	public Object onCall(MuleEventContext muleContext) throws Exception {
		Integer requestId = (Integer) muleContext.getMessage().getProperty("requestId", PropertyScope.INVOCATION);
		Integer requestId2 = (Integer) muleContext.getMessage().getInvocationProperty("requestId");  // alternative
		return null;

2 Replies to “Accessing mule flow variables from Java components”

  1. Hi, though it’s been a year since this has been posted, could you please explain how to call the UpdateBuffer class from a Java Invoke? I can’t figure out what to pass as arguments for the onCall method.

    1. You don’t invoke the onCall method directly from Java. I use the mule flow editor in anypoint studio (mule studio). Alternatively you can write the flow in XML.

Comments are closed.