org.springframework.config.java.context
Class JavaConfigApplicationContext

java.lang.Object
  extended by org.springframework.core.io.DefaultResourceLoader
      extended by org.springframework.context.support.AbstractApplicationContext
          extended by org.springframework.context.support.AbstractRefreshableApplicationContext
              extended by org.springframework.config.java.context.JavaConfigApplicationContext
All Implemented Interfaces:
BeanFactory, DisposableBean, HierarchicalBeanFactory, ListableBeanFactory, ApplicationContext, ApplicationEventPublisher, ConfigurableApplicationContext, Lifecycle, MessageSource, ResourceLoader, ResourcePatternResolver

public class JavaConfigApplicationContext
extends AbstractRefreshableApplicationContext

Application context that looks for classes annotated with the Configuration annotation and registers the Beans they define; is the primary programmatic resource for using Spring JavaConfig. Note that it is not strictly required that a configuration class be annotated with @Configuration, but rather that it exposes at least one non-private method annotated with @Bean.

Example

 JavaConfigApplicationContext context = new JavaConfigApplicationContext(AppConfig.class, DataConfig.class);
 
 AccountService accountService = (AccountService) context.getBean("accountService");
 
Where AppConfig and DataConfig are defined as follows:
 @Configuration
 public abstract class AppConfig {
     @Bean
     public AccountService accountService() {
         return new AccountService(dataSource());
     }
     @ExternalBean
     public abstract DataSource dataSource();
 }
 @Configuration
 public abstract class DataConfig {
     @Bean
     public DataSource dataSource() {
         return new DataSource(...);
     }
 }
 

Construction

The eight available constructors for JavaConfigApplicationContext are divided into two categories:

  1. Those that leave the context open for further configuration, and require the user to call refresh
  2. Those that leave the context closed for further configuration and do not require refresh
In the former set, the following code would be valid:
 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext();
 ctx.setConfigClasses(Config1.class, Config2.class);
 ctx.setBaseClasses("com.foo.myapp.config.*");
 ctx.setParent(anotherContext);
 ctx.refresh();
 Service myService = (Service) ctx.getBean("service");
 
Note that the caller must manually invoke refresh to advise the context that configuration is complete. In most cases, users will not want to be burdened with having to remember to do this, so the latter six constructors are provided as conveniences. They each internally call refresh, which means that any subsequent calls to setConfigClasses, setBasePackages or setParent are invalid and will result in an exception. Simply said, after instantiation with one of the convenience constructors, the context is 'closed for configuration':
 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config1.class, Config2.class);
 
 Service myService = (Service) ctx.getBean("service");
 

Type-safe access to beans

To ensure refactorability and avoid string-based bean lookups, it is recommended that users take advantage of JavaConfigApplicationContext's type-safe getBean methods: The examples above become more elegant using these methods:
 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config1.class, Config2.class);
 
 Service myService = ctx.getBean(Service.class); // no casting required!
 
Of course, if multiple beans of type Service exist in the context, the call above becomes ambiguous. Disambiguation can happen in one of two ways:
  1. Declare one bean as Primary
     @Configuration
     public class AppConfig {
         @Bean(primary=Primary.TRUE)
         public Service service() {
             return new Service(...);
         }
         @Bean
         public Service testService() {
             return new Service(...);
         }
     }
     
  2. Use the name-qualified getBean(Class, String) variant
     JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config1.class, Config2.class);
     
     Service testService = ctx.getBean(Service.class, "testService");
     

Author:
Chris Beams
See Also:
Configuration, Bean

Field Summary
 
Fields inherited from class org.springframework.context.support.AbstractApplicationContext
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, logger, MESSAGE_SOURCE_BEAN_NAME
 
Fields inherited from interface org.springframework.beans.factory.BeanFactory
FACTORY_BEAN_PREFIX
 
Fields inherited from interface org.springframework.context.ConfigurableApplicationContext
LOAD_TIME_WEAVER_BEAN_NAME
 
Fields inherited from interface org.springframework.core.io.support.ResourcePatternResolver
CLASSPATH_ALL_URL_PREFIX
 
Fields inherited from interface org.springframework.core.io.ResourceLoader
CLASSPATH_URL_PREFIX
 
Constructor Summary
JavaConfigApplicationContext()
          requires calling refresh() TODO: finish doc
JavaConfigApplicationContext(ApplicationContext parent)
          requires calling refresh() TODO: finish doc
JavaConfigApplicationContext(ApplicationContext parent, Class<?>... classes)
           
JavaConfigApplicationContext(ApplicationContext parent, Class<?>[] classes, String[] basePackages)
          TODO: Document
JavaConfigApplicationContext(ApplicationContext parent, String... basePackages)
           
JavaConfigApplicationContext(Class<?>... classes)
           
JavaConfigApplicationContext(Class<?>[] classes, String[] basePackages)
           
JavaConfigApplicationContext(String... basePackages)
           
 
Method Summary
 void addConfigClass(Class<?> cls)
          Allows for incrementally building up the configuration classes to be processed by this context.
protected  void finishRefresh()
           
protected  String[] getBasePackages()
           
<T> T
getBean(Class<T> type)
          Return an instance of the given type.
<T> T
getBean(Class<T> type, String beanName)
          Return an instance named beanName and of type type.
protected  Class<?>[] getConfigClasses()
           
protected  void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
           
protected  void prepareRefresh()
           
protected  void registerDefaultPostProcessors()
          Register the default post processors used for parsing Spring classes.
 void setBasePackages(String... basePackages)
          The base packages for configurations from Strings.
 void setConfigClasses(Class<?>... classes)
           
 void setParent(ApplicationContext context)
           
 
Methods inherited from class org.springframework.context.support.AbstractRefreshableApplicationContext
closeBeanFactory, createBeanFactory, customizeBeanFactory, getBeanFactory, hasBeanFactory, refreshBeanFactory
 
Methods inherited from class org.springframework.context.support.AbstractApplicationContext
addApplicationListener, addBeanFactoryPostProcessor, addListener, cancelRefresh, close, containsBean, containsBeanDefinition, containsLocalBean, destroy, destroyBeans, doClose, finishBeanFactoryInitialization, getAliases, getApplicationListeners, getAutowireCapableBeanFactory, getBean, getBean, getBean, getBeanDefinitionCount, getBeanDefinitionNames, getBeanFactoryPostProcessors, getBeanNamesForType, getBeanNamesForType, getBeansOfType, getBeansOfType, getDisplayName, getInternalParentBeanFactory, getInternalParentMessageSource, getMessage, getMessage, getMessage, getParent, getParentBeanFactory, getResourcePatternResolver, getResources, getStartupDate, getType, initApplicationEventMulticaster, initLifecycleDependentBeans, initMessageSource, invokeBeanFactoryPostProcessors, isActive, isPrototype, isRunning, isSingleton, isTypeMatch, obtainFreshBeanFactory, onClose, onRefresh, postProcessBeanFactory, prepareBeanFactory, publishEvent, refresh, registerBeanPostProcessors, registerListeners, registerShutdownHook, setDisplayName, start, stop, toString
 
Methods inherited from class org.springframework.core.io.DefaultResourceLoader
getClassLoader, getResource, getResourceByPath, setClassLoader
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.springframework.beans.factory.BeanFactory
containsBean, getAliases, getBean, getBean, getBean, getType, isPrototype, isSingleton, isTypeMatch
 
Methods inherited from interface org.springframework.core.io.ResourceLoader
getClassLoader, getResource
 

Constructor Detail

JavaConfigApplicationContext

public JavaConfigApplicationContext()
requires calling refresh() TODO: finish doc


JavaConfigApplicationContext

public JavaConfigApplicationContext(ApplicationContext parent)
requires calling refresh() TODO: finish doc

Parameters:
parent -

JavaConfigApplicationContext

public JavaConfigApplicationContext(String... basePackages)

JavaConfigApplicationContext

public JavaConfigApplicationContext(Class<?>... classes)

JavaConfigApplicationContext

public JavaConfigApplicationContext(ApplicationContext parent,
                                    Class<?>... classes)

JavaConfigApplicationContext

public JavaConfigApplicationContext(ApplicationContext parent,
                                    String... basePackages)

JavaConfigApplicationContext

public JavaConfigApplicationContext(Class<?>[] classes,
                                    String[] basePackages)

JavaConfigApplicationContext

public JavaConfigApplicationContext(ApplicationContext parent,
                                    Class<?>[] classes,
                                    String[] basePackages)
TODO: Document

Parameters:
parent -
classes -
basePackages -
See Also:
prepareRefresh(), finishRefresh()
Method Detail

prepareRefresh

protected void prepareRefresh()
Overrides:
prepareRefresh in class AbstractApplicationContext

setConfigClasses

public void setConfigClasses(Class<?>... classes)

addConfigClass

public void addConfigClass(Class<?> cls)
Allows for incrementally building up the configuration classes to be processed by this context. May only be called on a context still 'open for configuration' meaning that the user will need to manually call refresh() after all classes have been added.

Parameters:
cls -

setBasePackages

public void setBasePackages(String... basePackages)
The base packages for configurations from Strings. These use the same conventions as the component scanning introduced in Spring 2.5.


setParent

public void setParent(ApplicationContext context)
Specified by:
setParent in interface ConfigurableApplicationContext
Overrides:
setParent in class AbstractApplicationContext

getBasePackages

protected String[] getBasePackages()

getConfigClasses

protected Class<?>[] getConfigClasses()

finishRefresh

protected void finishRefresh()
Overrides:
finishRefresh in class AbstractApplicationContext

loadBeanDefinitions

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
                            throws IOException,
                                   BeansException
Specified by:
loadBeanDefinitions in class AbstractRefreshableApplicationContext
Throws:
IOException
BeansException

registerDefaultPostProcessors

protected void registerDefaultPostProcessors()
Register the default post processors used for parsing Spring classes.

See Also:
JavaConfigBeanFactoryPostProcessorRegistry

getBean

public <T> T getBean(Class<T> type)
Return an instance of the given type. If multiple instances of the same type exist, instances are inspected to see if exactly one is marked as Primary

Parameters:
type - desired instance type
Returns:
instance matching type
See Also:
Primary

getBean

public <T> T getBean(Class<T> type,
                     String beanName)
Return an instance named beanName and of type type. Useful in disambiguation cases where there is more than one bean of a given type within the factory and none is marked as Primary

This method is similar to its predecessor BeanFactory.getBean(String, Class), but this variant takes advantages of generics and removes the casting burden from the caller.



Copyright � 2005-2008 Spring Framework. All Rights Reserved.