View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.config.spring;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.config.ConfigurationException;
11  import org.mule.api.registry.Registry;
12  import org.mule.config.builders.AbstractConfigurationBuilder;
13  import org.mule.config.i18n.MessageFactory;
14  
15  import org.springframework.context.ApplicationContext;
16  import org.springframework.context.ConfigurableApplicationContext;
17  
18  /**
19   * Adds an existing Spring ApplicationContext to Mule's internal collection of Registries.
20   */
21  public class SpringConfigurationBuilder extends AbstractConfigurationBuilder
22  {
23      private ApplicationContext appContext;
24  
25      private ApplicationContext parentContext;
26      
27      public SpringConfigurationBuilder(ApplicationContext appContext)
28      {
29          this.appContext = appContext;
30      }
31  
32      public SpringConfigurationBuilder(ConfigurableApplicationContext appContext, ApplicationContext parentContext)
33      {
34          this.appContext = appContext;
35          this.parentContext = parentContext;
36      }
37  
38      protected void doConfigure(MuleContext muleContext) throws Exception
39      {
40          Registry registry;
41          
42          if (parentContext != null)
43          {
44              if (appContext instanceof ConfigurableApplicationContext)
45              {
46                  registry = new SpringRegistry((ConfigurableApplicationContext) appContext, parentContext, muleContext);
47              }
48              else
49              {
50                  throw new ConfigurationException(MessageFactory.createStaticMessage("Cannot set a parent context if the ApplicationContext does not implement ConfigurableApplicationContext"));
51              }
52          }
53          else
54          {
55              registry = new SpringRegistry(appContext, muleContext);
56          }
57  
58          // Note: The SpringRegistry must be created before applicationContext.refresh() gets called because
59          // some beans may try to look up other beans via the Registry during preInstantiateSingletons().
60          muleContext.addRegistry(registry);
61          registry.initialise();
62      }
63  
64  }