Over a million developers have joined DZone.

Implementing Shared Variables in Mule

DZone's Guide to

Implementing Shared Variables in Mule

Want to share your data across a project? See how you can create and implement shared variables in Mule to do just that using singleton Java POJOs.

· Integration Zone ·
Free Resource

Building integrations to CRM applications? Find out eight things that each product manager and technical executive should know in The CRM Integration Guide: 8 Things Experts Are Considering in Their API Strategy.

Ever wondered why session variables can't be shared across JMS transports?

I was trying to receive messages from a JMS Queue and, in case of an error, increment a counter until a threshold limit is reached. 

I tried setting a session variable in case of an exception and then incrementing it with:

<set-session-variable variableName="errorCounter" value="#[((sessionVars['errorCounter'] == null) ? 0 : sessionVars['errorCounter']) + new Integer(1).intValue()]"doc:name="Error Counter"/>

But as soon as the next thread of JMS Receiver starts, the session variable value is lost — it's null again.

The Workaround

  1. Create a POJO Java class with all the values we want to get and set in our Mule flows lying in the same project.

  2. Let's create a ErrorCounter.java class under src/main/java under the org.mule.utils package.

  3. package org.mule.utils;
    public class ErrorCounter {
        int errorCounter = 0;
        public int increment()
            return errorCounter;

    We can create getters and setters here, as we do in a JAVA POJO, and modify those functions as per our requirements.

  4. Next, create a singleton spring-bean instantiating the above class in your mule-config xml file.

        <spring:bean id="ErrorCounter" name="ErrorCounter"scope="singleton" class="org.mule.utils.ErrorCounter"/>

  5. Access these variables in mule flows using expressions to get and set the values. In this case, I am storing the value into a flow variable, which will have the value incremented when the next JMS Message is received.

    <set-variable variableName="errorCounter" value="#[app.registry['ErrorCounter'].increment();]" doc:name="Increment-Counter"/>

Hope this Helps. Thanks for reading!

Your API is not enough. Learn why (and how) leading SaaS providers are turning their products into platforms with API integration in the ebook, Build Platforms, Not Products from Cloud Elements.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}