Class GenericApplicationContext
- All Implemented Interfaces:
Closeable,AutoCloseable,org.springframework.beans.factory.BeanFactory,org.springframework.beans.factory.HierarchicalBeanFactory,org.springframework.beans.factory.ListableBeanFactory,org.springframework.beans.factory.support.BeanDefinitionRegistry,ApplicationContext,ApplicationEventPublisher,ConfigurableApplicationContext,Lifecycle,MessageSource,org.springframework.core.AliasRegistry,org.springframework.core.env.EnvironmentCapable,org.springframework.core.io.ResourceLoader,org.springframework.core.io.support.ResourcePatternResolver
- Direct Known Subclasses:
AnnotationConfigApplicationContext,GenericGroovyApplicationContext,GenericXmlApplicationContext,StaticApplicationContext
DefaultListableBeanFactory
instance and does not assume a specific bean definition format. Implements
the BeanDefinitionRegistry
interface in order to allow for applying any bean definition readers to it.
Typical usage is to register a variety of bean definitions via the
BeanDefinitionRegistry
interface and then call AbstractApplicationContext.refresh() to initialize those beans
with application context semantics (handling
ApplicationContextAware, auto-detecting
BeanFactoryPostProcessors,
etc).
In contrast to other ApplicationContext implementations that create a new
internal BeanFactory instance for each refresh, the internal BeanFactory of
this context is available right from the start, to be able to register bean
definitions on it. AbstractApplicationContext.refresh() may only be called once.
This ApplicationContext implementation is suitable for Ahead of Time
processing, using refreshForAotProcessing(org.springframework.aot.hint.RuntimeHints) as an alternative to the
regular AbstractApplicationContext.refresh().
Usage example:
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
ctx.refresh();
MyBean myBean = (MyBean) ctx.getBean("myBean");
...
For the typical case of XML bean definitions, you may also use
ClassPathXmlApplicationContext or FileSystemXmlApplicationContext,
which are easier to set up - but less flexible, since you can just use standard
resource locations for XML bean definitions, rather than mixing arbitrary bean
definition formats. For a custom application context implementation supposed to
read a specific bean definition format in a refreshable manner, consider
deriving from the AbstractRefreshableApplicationContext base class.- Since:
- 1.1.2
- Author:
- Juergen Hoeller, Chris Beams, Stephane Nicoll, Sam Brannen
- See Also:
-
registerBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)AbstractApplicationContext.refresh()XmlBeanDefinitionReaderPropertiesBeanDefinitionReader
-
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.core.io.DefaultResourceLoader
org.springframework.core.io.DefaultResourceLoader.ClassPathContextResource -
Field Summary
Fields inherited from class org.springframework.context.support.AbstractApplicationContext
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, LIFECYCLE_PROCESSOR_BEAN_NAME, logger, MESSAGE_SOURCE_BEAN_NAMEFields inherited from interface org.springframework.beans.factory.BeanFactory
FACTORY_BEAN_PREFIXFields inherited from interface org.springframework.context.ConfigurableApplicationContext
APPLICATION_STARTUP_BEAN_NAME, CONFIG_LOCATION_DELIMITERS, CONVERSION_SERVICE_BEAN_NAME, ENVIRONMENT_BEAN_NAME, LOAD_TIME_WEAVER_BEAN_NAME, SHUTDOWN_HOOK_THREAD_NAME, SYSTEM_ENVIRONMENT_BEAN_NAME, SYSTEM_PROPERTIES_BEAN_NAMEFields inherited from interface org.springframework.core.io.ResourceLoader
CLASSPATH_URL_PREFIXFields inherited from interface org.springframework.core.io.support.ResourcePatternResolver
CLASSPATH_ALL_URL_PREFIX -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new GenericApplicationContext.GenericApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory beanFactory) Create a new GenericApplicationContext with the given DefaultListableBeanFactory.GenericApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory beanFactory, ApplicationContext parent) Create a new GenericApplicationContext with the given DefaultListableBeanFactory.Create a new GenericApplicationContext with the given parent. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidCancel this context's refresh attempt, resetting theactiveflag after an exception got thrown.protected final voidNot much to do: We hold a single internal BeanFactory that will never get released.org.springframework.beans.factory.config.AutowireCapableBeanFactoryReturn this context's internal bean factory as AutowireCapableBeanFactory, if already available.org.springframework.beans.factory.config.BeanDefinitiongetBeanDefinition(String beanName) final org.springframework.beans.factory.config.ConfigurableListableBeanFactoryReturn the single internal BeanFactory held by this context (as ConfigurableListableBeanFactory).final org.springframework.beans.factory.support.DefaultListableBeanFactoryReturn the underlying bean factory of this context, available for registering bean definitions.org.springframework.core.io.ResourcegetResource(String location) This implementation delegates to this context'sResourceLoaderif set, falling back to the default superclass behavior otherwise.org.springframework.core.io.Resource[]getResources(String locationPattern) This implementation delegates to this context's ResourceLoader if it implements the ResourcePatternResolver interface, falling back to the default superclass behavior otherwise.booleanbooleanisBeanDefinitionOverridable(String beanName) booleanisBeanNameInUse(String beanName) protected final voidDo nothing: We hold a single internal BeanFactory and rely on callers to register beans through our public methods (or the BeanFactory's).voidrefreshForAotProcessing(org.springframework.aot.hint.RuntimeHints runtimeHints) Load or refresh the persistent representation of the configuration up to a point where the underlying bean factory is ready to create bean instances.voidregisterAlias(String beanName, String alias) <T> voidregisterBean(Class<T> beanClass, Object... constructorArgs) Register a bean from the given bean class, optionally providing explicit constructor arguments for consideration in the autowiring process.final <T> voidregisterBean(Class<T> beanClass, Supplier<T> supplier, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, using the given supplier for obtaining a new instance (typically declared as a lambda expression or method reference), optionally customizing its bean definition metadata (again typically declared as a lambda expression).final <T> voidregisterBean(Class<T> beanClass, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, optionally customizing its bean definition metadata (typically declared as a lambda expression).<T> voidregisterBean(String beanName, Class<T> beanClass, Object... constructorArgs) Register a bean from the given bean class, optionally providing explicit constructor arguments for consideration in the autowiring process.<T> voidregisterBean(String beanName, Class<T> beanClass, Supplier<T> supplier, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, using the given supplier for obtaining a new instance (typically declared as a lambda expression or method reference), optionally customizing its bean definition metadata (again typically declared as a lambda expression).final <T> voidregisterBean(String beanName, Class<T> beanClass, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, optionally customizing its bean definition metadata (typically declared as a lambda expression).voidregisterBeanDefinition(String beanName, org.springframework.beans.factory.config.BeanDefinition beanDefinition) voidremoveAlias(String alias) voidremoveBeanDefinition(String beanName) voidsetAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) Set whether it should be allowed to override bean definitions by registering a different definition with the same name, automatically replacing the former.voidsetAllowCircularReferences(boolean allowCircularReferences) Set whether to allow circular references between beans - and automatically try to resolve them.voidsetApplicationStartup(org.springframework.core.metrics.ApplicationStartup applicationStartup) Set theApplicationStartupfor this application context.voidsetClassLoader(ClassLoader classLoader) Specify the ClassLoader to load class path resources and bean classes with.voidsetParent(ApplicationContext parent) Set the parent of this application context, also setting the parent of the internal BeanFactory accordingly.voidsetResourceLoader(org.springframework.core.io.ResourceLoader resourceLoader) Set a ResourceLoader to use for this context.Methods inherited from class org.springframework.context.support.AbstractApplicationContext
addApplicationListener, addBeanFactoryPostProcessor, assertBeanFactoryActive, close, containsBean, containsBeanDefinition, containsLocalBean, createEnvironment, destroyBeans, doClose, findAllAnnotationsOnBean, findAnnotationOnBean, findAnnotationOnBean, finishBeanFactoryInitialization, finishRefresh, getAliases, getApplicationListeners, getApplicationName, getApplicationStartup, getBean, getBean, getBean, getBean, getBean, getBeanDefinitionCount, getBeanDefinitionNames, getBeanFactoryPostProcessors, getBeanNamesForAnnotation, getBeanNamesForType, getBeanNamesForType, getBeanNamesForType, getBeanNamesForType, getBeanProvider, getBeanProvider, getBeanProvider, getBeanProvider, getBeansOfType, getBeansOfType, getBeansWithAnnotation, getDisplayName, getEnvironment, getId, getInternalParentBeanFactory, getInternalParentMessageSource, getMessage, getMessage, getMessage, getParent, getParentBeanFactory, getResourcePatternResolver, getStartupDate, getType, getType, initApplicationEventMulticaster, initLifecycleProcessor, initMessageSource, initPropertySources, invokeBeanFactoryPostProcessors, isActive, isPrototype, isRunning, isSingleton, isTypeMatch, isTypeMatch, obtainFreshBeanFactory, onClose, onRefresh, postProcessBeanFactory, prepareBeanFactory, prepareRefresh, publishEvent, publishEvent, publishEvent, refresh, registerBeanPostProcessors, registerListeners, registerShutdownHook, removeApplicationListener, resetCommonCaches, setDisplayName, setEnvironment, setId, start, stop, toStringMethods inherited from class org.springframework.core.io.DefaultResourceLoader
addProtocolResolver, clearResourceCaches, getProtocolResolvers, getResourceByPath, getResourceCacheMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.springframework.core.AliasRegistry
getAliasesMethods inherited from interface org.springframework.beans.factory.support.BeanDefinitionRegistry
containsBeanDefinition, getBeanDefinitionCount, getBeanDefinitionNamesMethods inherited from interface org.springframework.context.ConfigurableApplicationContext
addProtocolResolver
-
Constructor Details
-
GenericApplicationContext
public GenericApplicationContext()Create a new GenericApplicationContext. -
GenericApplicationContext
public GenericApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory beanFactory) Create a new GenericApplicationContext with the given DefaultListableBeanFactory.- Parameters:
beanFactory- the DefaultListableBeanFactory instance to use for this context- See Also:
-
GenericApplicationContext
Create a new GenericApplicationContext with the given parent.- Parameters:
parent- the parent application context- See Also:
-
GenericApplicationContext
public GenericApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory beanFactory, ApplicationContext parent) Create a new GenericApplicationContext with the given DefaultListableBeanFactory.- Parameters:
beanFactory- the DefaultListableBeanFactory instance to use for this contextparent- the parent application context- See Also:
-
-
Method Details
-
setParent
Set the parent of this application context, also setting the parent of the internal BeanFactory accordingly.- Specified by:
setParentin interfaceConfigurableApplicationContext- Overrides:
setParentin classAbstractApplicationContext- Parameters:
parent- the parent context- See Also:
-
ConfigurableBeanFactory.setParentBeanFactory(org.springframework.beans.factory.BeanFactory)
-
setApplicationStartup
public void setApplicationStartup(org.springframework.core.metrics.ApplicationStartup applicationStartup) Description copied from interface:ConfigurableApplicationContextSet theApplicationStartupfor this application context.This allows the application context to record metrics during startup.
- Specified by:
setApplicationStartupin interfaceConfigurableApplicationContext- Overrides:
setApplicationStartupin classAbstractApplicationContext- Parameters:
applicationStartup- the new context event factory
-
setAllowBeanDefinitionOverriding
public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) Set whether it should be allowed to override bean definitions by registering a different definition with the same name, automatically replacing the former. If not, an exception will be thrown. Default is "true".- Since:
- 3.0
- See Also:
-
DefaultListableBeanFactory.setAllowBeanDefinitionOverriding(boolean)
-
setAllowCircularReferences
public void setAllowCircularReferences(boolean allowCircularReferences) Set whether to allow circular references between beans - and automatically try to resolve them.Default is "true". Turn this off to throw an exception when encountering a circular reference, disallowing them completely.
- Since:
- 3.0
- See Also:
-
AbstractAutowireCapableBeanFactory.setAllowCircularReferences(boolean)
-
setResourceLoader
public void setResourceLoader(org.springframework.core.io.ResourceLoader resourceLoader) Set a ResourceLoader to use for this context. If set, the context will delegate allgetResourcecalls to the given ResourceLoader. If not set, default resource loading will apply.The main reason to specify a custom ResourceLoader is to resolve resource paths (without URL prefix) in a specific fashion. The default behavior is to resolve such paths as class path locations. To resolve resource paths as file system locations, specify a FileSystemResourceLoader here.
You can also pass in a full ResourcePatternResolver, which will be autodetected by the context and used for
getResourcescalls as well. Else, default resource pattern matching will apply.- See Also:
-
getResource(java.lang.String)DefaultResourceLoaderFileSystemResourceLoaderResourcePatternResolvergetResources(java.lang.String)
-
getResource
This implementation delegates to this context'sResourceLoaderif set, falling back to the default superclass behavior otherwise.As of Spring Framework 5.3.22, this method also honors registered protocol resolvers when a custom
ResourceLoaderhas been set.- Specified by:
getResourcein interfaceorg.springframework.core.io.ResourceLoader- Overrides:
getResourcein classorg.springframework.core.io.DefaultResourceLoader- See Also:
-
setResourceLoader(ResourceLoader)DefaultResourceLoader.addProtocolResolver(ProtocolResolver)
-
getResources
public org.springframework.core.io.Resource[] getResources(String locationPattern) throws IOException This implementation delegates to this context's ResourceLoader if it implements the ResourcePatternResolver interface, falling back to the default superclass behavior otherwise.- Specified by:
getResourcesin interfaceorg.springframework.core.io.support.ResourcePatternResolver- Overrides:
getResourcesin classAbstractApplicationContext- Throws:
IOException- See Also:
-
setClassLoader
Description copied from interface:ConfigurableApplicationContextSpecify the ClassLoader to load class path resources and bean classes with.This context class loader will be passed to the internal bean factory.
- Specified by:
setClassLoaderin interfaceConfigurableApplicationContext- Overrides:
setClassLoaderin classorg.springframework.core.io.DefaultResourceLoader- See Also:
-
DefaultResourceLoader(ClassLoader)ConfigurableBeanFactory.setBeanClassLoader(java.lang.ClassLoader)
-
getClassLoader
- Specified by:
getClassLoaderin interfaceorg.springframework.core.io.ResourceLoader- Overrides:
getClassLoaderin classorg.springframework.core.io.DefaultResourceLoader
-
refreshBeanFactory
Do nothing: We hold a single internal BeanFactory and rely on callers to register beans through our public methods (or the BeanFactory's).- Specified by:
refreshBeanFactoryin classAbstractApplicationContext- Throws:
IllegalStateException- if already initialized and multiple refresh attempts are not supported- See Also:
-
cancelRefresh
Description copied from class:AbstractApplicationContextCancel this context's refresh attempt, resetting theactiveflag after an exception got thrown.- Overrides:
cancelRefreshin classAbstractApplicationContext- Parameters:
ex- the exception that led to the cancellation
-
closeBeanFactory
protected final void closeBeanFactory()Not much to do: We hold a single internal BeanFactory that will never get released.- Specified by:
closeBeanFactoryin classAbstractApplicationContext
-
getBeanFactory
public final org.springframework.beans.factory.config.ConfigurableListableBeanFactory getBeanFactory()Return the single internal BeanFactory held by this context (as ConfigurableListableBeanFactory).- Specified by:
getBeanFactoryin interfaceConfigurableApplicationContext- Specified by:
getBeanFactoryin classAbstractApplicationContext- Returns:
- this application context's internal bean factory (never
null) - See Also:
-
getDefaultListableBeanFactory
public final org.springframework.beans.factory.support.DefaultListableBeanFactory getDefaultListableBeanFactory()Return the underlying bean factory of this context, available for registering bean definitions.NOTE: You need to call
AbstractApplicationContext.refresh()to initialize the bean factory and its contained beans with application context semantics (autodetecting BeanFactoryPostProcessors, etc).- Returns:
- the internal bean factory (as DefaultListableBeanFactory)
-
getAutowireCapableBeanFactory
public org.springframework.beans.factory.config.AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateExceptionDescription copied from class:AbstractApplicationContextReturn this context's internal bean factory as AutowireCapableBeanFactory, if already available.- Specified by:
getAutowireCapableBeanFactoryin interfaceApplicationContext- Overrides:
getAutowireCapableBeanFactoryin classAbstractApplicationContext- Returns:
- the AutowireCapableBeanFactory for this context
- Throws:
IllegalStateException- if the context does not support theAutowireCapableBeanFactoryinterface, or does not hold an autowire-capable bean factory yet (e.g. ifrefresh()has never been called), or if the context has been closed already- See Also:
-
registerBeanDefinition
public void registerBeanDefinition(String beanName, org.springframework.beans.factory.config.BeanDefinition beanDefinition) throws org.springframework.beans.factory.BeanDefinitionStoreException - Specified by:
registerBeanDefinitionin interfaceorg.springframework.beans.factory.support.BeanDefinitionRegistry- Throws:
org.springframework.beans.factory.BeanDefinitionStoreException
-
removeBeanDefinition
public void removeBeanDefinition(String beanName) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
removeBeanDefinitionin interfaceorg.springframework.beans.factory.support.BeanDefinitionRegistry- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
getBeanDefinition
public org.springframework.beans.factory.config.BeanDefinition getBeanDefinition(String beanName) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
getBeanDefinitionin interfaceorg.springframework.beans.factory.support.BeanDefinitionRegistry- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
isBeanDefinitionOverridable
- Specified by:
isBeanDefinitionOverridablein interfaceorg.springframework.beans.factory.support.BeanDefinitionRegistry
-
isBeanNameInUse
- Specified by:
isBeanNameInUsein interfaceorg.springframework.beans.factory.support.BeanDefinitionRegistry
-
registerAlias
- Specified by:
registerAliasin interfaceorg.springframework.core.AliasRegistry
-
removeAlias
- Specified by:
removeAliasin interfaceorg.springframework.core.AliasRegistry
-
isAlias
- Specified by:
isAliasin interfaceorg.springframework.core.AliasRegistry
-
refreshForAotProcessing
public void refreshForAotProcessing(org.springframework.aot.hint.RuntimeHints runtimeHints) Load or refresh the persistent representation of the configuration up to a point where the underlying bean factory is ready to create bean instances.This variant of
AbstractApplicationContext.refresh()is used by Ahead of Time (AOT) processing that optimizes the application context, typically at build time.In this mode, only
BeanDefinitionRegistryPostProcessorandMergedBeanDefinitionPostProcessorare invoked.- Parameters:
runtimeHints- the runtime hints- Throws:
org.springframework.beans.BeansException- if the bean factory could not be initializedIllegalStateException- if already initialized and multiple refresh attempts are not supported- Since:
- 6.0
-
registerBean
Register a bean from the given bean class, optionally providing explicit constructor arguments for consideration in the autowiring process.- Parameters:
beanClass- the class of the beanconstructorArgs- custom argument values to be fed into Spring's constructor resolution algorithm, resolving either all arguments or just specific ones, with the rest to be resolved through regular autowiring (may benullor empty)- Since:
- 5.2 (since 5.0 on the AnnotationConfigApplicationContext subclass)
-
registerBean
public <T> void registerBean(@Nullable String beanName, Class<T> beanClass, Object... constructorArgs) Register a bean from the given bean class, optionally providing explicit constructor arguments for consideration in the autowiring process.- Parameters:
beanName- the name of the bean (may benull)beanClass- the class of the beanconstructorArgs- custom argument values to be fed into Spring's constructor resolution algorithm, resolving either all arguments or just specific ones, with the rest to be resolved through regular autowiring (may benullor empty)- Since:
- 5.2 (since 5.0 on the AnnotationConfigApplicationContext subclass)
-
registerBean
public final <T> void registerBean(Class<T> beanClass, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, optionally customizing its bean definition metadata (typically declared as a lambda expression).- Parameters:
beanClass- the class of the bean (resolving a public constructor to be autowired, possibly simply the default constructor)customizers- one or more callbacks for customizing the factory'sBeanDefinition, e.g. setting a lazy-init or primary flag- Since:
- 5.0
- See Also:
-
registerBean
public final <T> void registerBean(@Nullable String beanName, Class<T> beanClass, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, optionally customizing its bean definition metadata (typically declared as a lambda expression).- Parameters:
beanName- the name of the bean (may benull)beanClass- the class of the bean (resolving a public constructor to be autowired, possibly simply the default constructor)customizers- one or more callbacks for customizing the factory'sBeanDefinition, e.g. setting a lazy-init or primary flag- Since:
- 5.0
- See Also:
-
registerBean
public final <T> void registerBean(Class<T> beanClass, Supplier<T> supplier, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, using the given supplier for obtaining a new instance (typically declared as a lambda expression or method reference), optionally customizing its bean definition metadata (again typically declared as a lambda expression).- Parameters:
beanClass- the class of the beansupplier- a callback for creating an instance of the beancustomizers- one or more callbacks for customizing the factory'sBeanDefinition, e.g. setting a lazy-init or primary flag- Since:
- 5.0
- See Also:
-
registerBean
public <T> void registerBean(@Nullable String beanName, Class<T> beanClass, @Nullable Supplier<T> supplier, org.springframework.beans.factory.config.BeanDefinitionCustomizer... customizers) Register a bean from the given bean class, using the given supplier for obtaining a new instance (typically declared as a lambda expression or method reference), optionally customizing its bean definition metadata (again typically declared as a lambda expression).This method can be overridden to adapt the registration mechanism for all
registerBeanmethods (since they all delegate to this one).- Parameters:
beanName- the name of the bean (may benull)beanClass- the class of the beansupplier- a callback for creating an instance of the bean (in case ofnull, resolving a public constructor to be autowired instead)customizers- one or more callbacks for customizing the factory'sBeanDefinition, e.g. setting a lazy-init or primary flag- Since:
- 5.0
-