Contact Us 1-800-596-4880

Spring Application Contexts

This page describes the options available for controlling how Mule creates and manages Spring application contexts for your application.

Single Application Context

By default, Mule will combine all resource files into a single ApplicationContext, whether they are "pure" Spring files or Mule configuration files. For example, the following code will create a single application context consisting of the objects in spring-beans.xml plus the objects in mule-config.xml:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder = new SpringXmlConfigurationBuilder("spring-beans.xml, mule-config.xml");
builder.configure(muleContext);

muleContext.start();

Or, in a more abbreviated form, the single application context can be defined like so:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(
                               new SpringXmlConfigurationBuilder("spring-beans.xml, mule-config.xml"));
muleContext.start();

Multiple Application Contexts

You can instruct Mule to create a separate application context for each Mule configuration file. The following code will create two application contexts, one for each configuration resource:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder1 = new SpringXmlConfigurationBuilder("spring-beans.xml");
builder1.configure(muleContext);

ConfigurationBuilder builder2 = new SpringXmlConfigurationBuilder("mule-config.xml");
builder2.configure(muleContext);

muleContext.start();

Using an Existing Application Context

If you already have an application context, you can instruct Mule to use it as follows:

ApplicationContext myAppContext = getMyAppContextFromSomewhereElse();

ConfigurationBuilder builder1 = new SpringConfigurationBuilder(myAppContext);
ConfigurationBuilder builder2 = new SpringXmlConfigurationBuilder("mule-config.xml");

List bList = new ArrayList();
bList.add(builder1);
bList.add(builder2);

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(bList);

muleContext.start();

Using an Existing Application Context as Parent

You can designate an existing application context as a parent context for Mule, so that the Mule configuration can refer to and/or override beans in the application context:

ApplicationContext myAppContext = getMyAppContextFromSomewhereElse();

ConfigurationBuilder builder = new SpringXmlConfigurationBuilder("mule-config.xml");
builder.setParentContext(myAppContext);

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(builder);
muleContext.start();

The MuleXmlBuilderContextListener class checks to see if an application context (WebApplicationContext) has already been created by Spring, and if there is one, Mule uses it as the parent automatically.