Class AbstractApplicationContext
- All Implemented Interfaces:
Closeable,AutoCloseable,org.springframework.beans.factory.BeanFactory,org.springframework.beans.factory.HierarchicalBeanFactory,org.springframework.beans.factory.ListableBeanFactory,ApplicationContext,ApplicationEventPublisher,ConfigurableApplicationContext,Lifecycle,MessageSource,org.springframework.core.env.EnvironmentCapable,org.springframework.core.io.ResourceLoader,org.springframework.core.io.support.ResourcePatternResolver
- Direct Known Subclasses:
AbstractRefreshableApplicationContext,GenericApplicationContext
ApplicationContext
interface. Doesn't mandate the type of storage used for configuration; simply
implements common context functionality. Uses the Template Method design pattern,
requiring concrete subclasses to implement abstract methods.
In contrast to a plain BeanFactory, an ApplicationContext is supposed
to detect special beans defined in its internal bean factory:
Therefore, this class automatically registers
BeanFactoryPostProcessors,
BeanPostProcessors,
and ApplicationListeners
which are defined as beans in the context.
A MessageSource may also be supplied
as a bean in the context, with the name "messageSource"; otherwise, message
resolution is delegated to the parent context. Furthermore, a multicaster
for application events can be supplied as an "applicationEventMulticaster" bean
of type ApplicationEventMulticaster
in the context; otherwise, a default multicaster of type
SimpleApplicationEventMulticaster will be used.
Implements resource loading by extending
DefaultResourceLoader.
Consequently treats non-URL resource paths as class path resources
(supporting full class path resource names that include the package path,
e.g. "mypackage/myresource.dat"), unless the DefaultResourceLoader.getResourceByPath(java.lang.String)
method is overridden in a subclass.
- Since:
- January 21, 2001
- Author:
- Rod Johnson, Juergen Hoeller, Mark Fisher, Stephane Nicoll, Sam Brannen, Sebastien Deleuze, Brian Clozel
- See Also:
-
refreshBeanFactory()getBeanFactory()BeanFactoryPostProcessorBeanPostProcessorApplicationEventMulticasterApplicationListenerMessageSource
-
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.core.io.DefaultResourceLoader
org.springframework.core.io.DefaultResourceLoader.ClassPathContextResource -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe name of theApplicationEventMulticasterbean in the context.static final StringThe name of theLifecycleProcessorbean in the context.protected final org.apache.commons.logging.LogLogger used by this class.static final StringThe name of theMessageSourcebean in the context.Fields 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 AbstractApplicationContext with no parent.Create a new AbstractApplicationContext with the given parent context. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddApplicationListener(ApplicationListener<?> listener) Add a new ApplicationListener that will be notified on context events such as context refresh and context shutdown.voidaddBeanFactoryPostProcessor(org.springframework.beans.factory.config.BeanFactoryPostProcessor postProcessor) Add a new BeanFactoryPostProcessor that will get applied to the internal bean factory of this application context on refresh, before any of the bean definitions get evaluated.protected voidAssert that this context's BeanFactory is currently active, throwing anIllegalStateExceptionif it isn't.protected voidCancel this context's refresh attempt, resetting theactiveflag after an exception got thrown.voidclose()Close this application context, destroying all beans in its bean factory.protected abstract voidSubclasses must implement this method to release their internal bean factory.booleancontainsBean(String name) booleancontainsBeanDefinition(String beanName) booleancontainsLocalBean(String name) protected org.springframework.core.env.ConfigurableEnvironmentCreate and return a newStandardEnvironment.protected voidTemplate method for destroying all beans that this context manages.protected voiddoClose()Actually performs context closing: publishes a ContextClosedEvent and destroys the singletons in the bean factory of this application context.<A extends Annotation>
Set<A>findAllAnnotationsOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) <A extends Annotation>
AfindAnnotationOnBean(String beanName, Class<A> annotationType) <A extends Annotation>
AfindAnnotationOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) protected voidfinishBeanFactoryInitialization(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Finish the initialization of this context's bean factory, initializing all remaining singleton beans.protected voidFinish the refresh of this context, invoking the LifecycleProcessor's onRefresh() method and publishing theContextRefreshedEvent.String[]getAliases(String name) Return the list of statically specified ApplicationListeners.Return a name for the deployed application that this context belongs to.org.springframework.core.metrics.ApplicationStartupReturn theApplicationStartupfor this application context.org.springframework.beans.factory.config.AutowireCapableBeanFactoryReturn this context's internal bean factory as AutowireCapableBeanFactory, if already available.<T> T<T> T<T> TintString[]abstract org.springframework.beans.factory.config.ConfigurableListableBeanFactorySubclasses must return their internal bean factory here.List<org.springframework.beans.factory.config.BeanFactoryPostProcessor>Return the list of BeanFactoryPostProcessors that will get applied to the internal BeanFactory.String[]getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) String[]getBeanNamesForType(Class<?> type) String[]getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) String[]getBeanNamesForType(org.springframework.core.ResolvableType type) String[]getBeanNamesForType(org.springframework.core.ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) <T> org.springframework.beans.factory.ObjectProvider<T>getBeanProvider(Class<T> requiredType) <T> org.springframework.beans.factory.ObjectProvider<T>getBeanProvider(Class<T> requiredType, boolean allowEagerInit) <T> org.springframework.beans.factory.ObjectProvider<T>getBeanProvider(org.springframework.core.ResolvableType requiredType) <T> org.springframework.beans.factory.ObjectProvider<T>getBeanProvider(org.springframework.core.ResolvableType requiredType, boolean allowEagerInit) getBeansOfType(Class<T> type) getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) getBeansWithAnnotation(Class<? extends Annotation> annotationType) Return a friendly name for this context.org.springframework.core.env.ConfigurableEnvironmentReturn theEnvironmentfor this application context in configurable form, allowing for further customization.getId()Return the unique id of this application context.protected org.springframework.beans.factory.BeanFactoryReturn the internal bean factory of the parent context if it implements ConfigurableApplicationContext; else, return the parent context itself.protected MessageSourceReturn the internal message source of the parent context if it is an AbstractApplicationContext too; else, return the parent context itself.getMessage(String code, Object[] args, String defaultMessage, Locale locale) Try to resolve the message.getMessage(String code, Object[] args, Locale locale) Try to resolve the message.getMessage(MessageSourceResolvable resolvable, Locale locale) Try to resolve the message using all the attributes contained within theMessageSourceResolvableargument that was passed in.Return the parent context, ornullif there is no parent (that is, this context is the root of the context hierarchy).org.springframework.beans.factory.BeanFactoryprotected org.springframework.core.io.support.ResourcePatternResolverReturn the ResourcePatternResolver to use for resolving location patterns into Resource instances.org.springframework.core.io.Resource[]getResources(String locationPattern) longReturn the timestamp (ms) when this context was first loaded.Class<?>Class<?>protected voidInitialize theApplicationEventMulticaster.protected voidInitialize theLifecycleProcessor.protected voidInitialize theMessageSource.protected voidReplace any stub property sources with actual instances.protected voidinvokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Instantiate and invoke all registered BeanFactoryPostProcessor beans, respecting explicit order if given.booleanisActive()Determine whether this application context is active, that is, whether it has been refreshed at least once and has not been closed yet.booleanisPrototype(String name) booleanCheck whether this component is currently running.booleanisSingleton(String name) booleanisTypeMatch(String name, Class<?> typeToMatch) booleanisTypeMatch(String name, org.springframework.core.ResolvableType typeToMatch) protected org.springframework.beans.factory.config.ConfigurableListableBeanFactoryTell the subclass to refresh the internal bean factory.protected voidonClose()Template method which can be overridden to add context-specific shutdown work.protected voidTemplate method which can be overridden to add context-specific refresh work.protected voidpostProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Modify the application context's internal bean factory after its standard initialization.protected voidprepareBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.protected voidPrepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources.voidpublishEvent(Object event) Publish the given event to all listeners.protected voidpublishEvent(Object event, org.springframework.core.ResolvableType typeHint) Publish the given event to all listeners.voidpublishEvent(ApplicationEvent event) Publish the given event to all listeners.voidrefresh()Load or refresh the persistent representation of the configuration, which might be from Java-based configuration, an XML file, a properties file, a relational database schema, or some other format.protected abstract voidSubclasses must implement this method to perform the actual configuration load.protected voidregisterBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Instantiate and register all BeanPostProcessor beans, respecting explicit order if given.protected voidAdd beans that implement ApplicationListener as listeners.voidRegister a shutdown hook namedSpringContextShutdownHookwith the JVM runtime, closing this context on JVM shutdown unless it has already been closed at that time.voidremoveApplicationListener(ApplicationListener<?> listener) Remove the given ApplicationListener from this context's set of listeners, assuming it got registered viaConfigurableApplicationContext.addApplicationListener(org.springframework.context.ApplicationListener<?>)before.protected voidReset Spring's common reflection metadata caches, in particular theReflectionUtils,AnnotationUtils,ResolvableTypeandCachedIntrospectionResultscaches.voidsetApplicationStartup(org.springframework.core.metrics.ApplicationStartup applicationStartup) Set theApplicationStartupfor this application context.voidsetDisplayName(String displayName) Set a friendly name for this context.voidsetEnvironment(org.springframework.core.env.ConfigurableEnvironment environment) Set theEnvironmentfor this application context.voidSet the unique id of this application context.voidsetParent(ApplicationContext parent) Set the parent of this application context.voidstart()Start this component.voidstop()Stop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method.toString()Return information about this context.Methods inherited from class org.springframework.core.io.DefaultResourceLoader
addProtocolResolver, clearResourceCaches, getClassLoader, getProtocolResolvers, getResource, getResourceByPath, getResourceCache, setClassLoaderMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.springframework.context.ConfigurableApplicationContext
addProtocolResolver, setClassLoaderMethods inherited from interface org.springframework.core.io.ResourceLoader
getClassLoader, getResource
-
Field Details
-
MESSAGE_SOURCE_BEAN_NAME
The name of theMessageSourcebean in the context. If none is supplied, message resolution is delegated to the parent. -
APPLICATION_EVENT_MULTICASTER_BEAN_NAME
The name of theApplicationEventMulticasterbean in the context. If none is supplied, aSimpleApplicationEventMulticasteris used. -
LIFECYCLE_PROCESSOR_BEAN_NAME
The name of theLifecycleProcessorbean in the context. If none is supplied, aDefaultLifecycleProcessoris used.- Since:
- 3.0
- See Also:
-
logger
protected final org.apache.commons.logging.Log loggerLogger used by this class. Available to subclasses.
-
-
Constructor Details
-
AbstractApplicationContext
public AbstractApplicationContext()Create a new AbstractApplicationContext with no parent. -
AbstractApplicationContext
Create a new AbstractApplicationContext with the given parent context.- Parameters:
parent- the parent context
-
-
Method Details
-
setId
Set the unique id of this application context.Default is the object id of the context instance, or the name of the context bean if the context is itself defined as a bean.
- Specified by:
setIdin interfaceConfigurableApplicationContext- Parameters:
id- the unique id of the context
-
getId
Description copied from interface:ApplicationContextReturn the unique id of this application context.- Specified by:
getIdin interfaceApplicationContext- Returns:
- the unique id of the context, or
nullif none
-
getApplicationName
Description copied from interface:ApplicationContextReturn a name for the deployed application that this context belongs to.- Specified by:
getApplicationNamein interfaceApplicationContext- Returns:
- a name for the deployed application, or the empty String by default
-
setDisplayName
Set a friendly name for this context. Typically done during initialization of concrete context implementations.Default is the object id of the context instance.
-
getDisplayName
Return a friendly name for this context.- Specified by:
getDisplayNamein interfaceApplicationContext- Returns:
- a display name for this context (never
null)
-
getParent
Return the parent context, ornullif there is no parent (that is, this context is the root of the context hierarchy).- Specified by:
getParentin interfaceApplicationContext- Returns:
- the parent context, or
nullif there is no parent
-
setEnvironment
public void setEnvironment(org.springframework.core.env.ConfigurableEnvironment environment) Set theEnvironmentfor this application context.Default value is determined by
createEnvironment(). Replacing the default with this method is one option but configuration throughgetEnvironment()should also be considered. In either case, such modifications should be performed beforerefresh().- Specified by:
setEnvironmentin interfaceConfigurableApplicationContext- Parameters:
environment- the new environment- See Also:
-
getEnvironment
public org.springframework.core.env.ConfigurableEnvironment getEnvironment()Return theEnvironmentfor this application context in configurable form, allowing for further customization.If none specified, a default environment will be initialized via
createEnvironment().- Specified by:
getEnvironmentin interfaceConfigurableApplicationContext- Specified by:
getEnvironmentin interfaceorg.springframework.core.env.EnvironmentCapable
-
createEnvironment
protected org.springframework.core.env.ConfigurableEnvironment createEnvironment()Create and return a newStandardEnvironment.Subclasses may override this method in order to supply a custom
ConfigurableEnvironmentimplementation. -
getAutowireCapableBeanFactory
public org.springframework.beans.factory.config.AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateExceptionReturn this context's internal bean factory as AutowireCapableBeanFactory, if already available.- Specified by:
getAutowireCapableBeanFactoryin interfaceApplicationContext- 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:
-
getStartupDate
public long getStartupDate()Return the timestamp (ms) when this context was first loaded.- Specified by:
getStartupDatein interfaceApplicationContext- Returns:
- the timestamp (ms) when this context was first loaded
-
publishEvent
Publish the given event to all listeners.Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannot publish events.
- Specified by:
publishEventin interfaceApplicationEventPublisher- Parameters:
event- the event to publish (may be application-specific or a standard framework event)- See Also:
-
publishEvent
Publish the given event to all listeners.Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannot publish events.
- Specified by:
publishEventin interfaceApplicationEventPublisher- Parameters:
event- the event to publish (may be anApplicationEventor a payload object to be turned into aPayloadApplicationEvent)- See Also:
-
publishEvent
protected void publishEvent(Object event, @Nullable org.springframework.core.ResolvableType typeHint) Publish the given event to all listeners.This is the internal delegate that all other
publishEventmethods refer to. It is not meant to be called directly but rather serves as a propagation mechanism between application contexts in a hierarchy, potentially overridden in subclasses for a custom propagation arrangement.- Parameters:
event- the event to publish (may be anApplicationEventor a payload object to be turned into aPayloadApplicationEvent)typeHint- the resolved event type, if known. The implementation of this method also tolerates a payload type hint for a payload object to be turned into aPayloadApplicationEvent. However, the recommended way is to construct an actual event object viaPayloadApplicationEvent(Object, Object, ResolvableType)instead for such scenarios.- Since:
- 4.2
- See Also:
-
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- Parameters:
applicationStartup- the new context event factory
-
getApplicationStartup
public org.springframework.core.metrics.ApplicationStartup getApplicationStartup()Description copied from interface:ConfigurableApplicationContextReturn theApplicationStartupfor this application context.- Specified by:
getApplicationStartupin interfaceConfigurableApplicationContext
-
getResourcePatternResolver
protected org.springframework.core.io.support.ResourcePatternResolver getResourcePatternResolver()Return the ResourcePatternResolver to use for resolving location patterns into Resource instances. Default is aPathMatchingResourcePatternResolver, supporting Ant-style location patterns.Can be overridden in subclasses, for extended resolution strategies, for example in a web environment.
Do not call this when needing to resolve a location pattern. Call the context's
getResourcesmethod instead, which will delegate to the ResourcePatternResolver.- Returns:
- the ResourcePatternResolver for this context
- See Also:
-
getResources(java.lang.String)PathMatchingResourcePatternResolver
-
setParent
Set the parent of this application context.The parent environment is merged with this (child) application context environment if the parent is non-
nulland its environment is an instance ofConfigurableEnvironment.- Specified by:
setParentin interfaceConfigurableApplicationContext- Parameters:
parent- the parent context- See Also:
-
ConfigurableEnvironment.merge(ConfigurableEnvironment)
-
addBeanFactoryPostProcessor
public void addBeanFactoryPostProcessor(org.springframework.beans.factory.config.BeanFactoryPostProcessor postProcessor) Description copied from interface:ConfigurableApplicationContextAdd a new BeanFactoryPostProcessor that will get applied to the internal bean factory of this application context on refresh, before any of the bean definitions get evaluated. To be invoked during context configuration.- Specified by:
addBeanFactoryPostProcessorin interfaceConfigurableApplicationContext- Parameters:
postProcessor- the factory processor to register
-
getBeanFactoryPostProcessors
public List<org.springframework.beans.factory.config.BeanFactoryPostProcessor> getBeanFactoryPostProcessors()Return the list of BeanFactoryPostProcessors that will get applied to the internal BeanFactory. -
addApplicationListener
Description copied from interface:ConfigurableApplicationContextAdd a new ApplicationListener that will be notified on context events such as context refresh and context shutdown.Note that any ApplicationListener registered here will be applied on refresh if the context is not active yet, or on the fly with the current event multicaster in case of a context that is already active.
- Specified by:
addApplicationListenerin interfaceConfigurableApplicationContext- Parameters:
listener- the ApplicationListener to register- See Also:
-
removeApplicationListener
Description copied from interface:ConfigurableApplicationContextRemove the given ApplicationListener from this context's set of listeners, assuming it got registered viaConfigurableApplicationContext.addApplicationListener(org.springframework.context.ApplicationListener<?>)before.- Specified by:
removeApplicationListenerin interfaceConfigurableApplicationContext- Parameters:
listener- the ApplicationListener to deregister
-
getApplicationListeners
Return the list of statically specified ApplicationListeners. -
refresh
Description copied from interface:ConfigurableApplicationContextLoad or refresh the persistent representation of the configuration, which might be from Java-based configuration, an XML file, a properties file, a relational database schema, or some other format.As this is a startup method, it should destroy already created singletons if it fails, to avoid dangling resources. In other words, after invocation of this method, either all or no singletons at all should be instantiated.
- Specified by:
refreshin interfaceConfigurableApplicationContext- Throws:
org.springframework.beans.BeansException- if the bean factory could not be initializedIllegalStateException- if already initialized and multiple refresh attempts are not supported
-
prepareRefresh
protected void prepareRefresh()Prepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources. -
initPropertySources
protected void initPropertySources()Replace any stub property sources with actual instances.
- See Also:
-
PropertySource.StubPropertySourceorg.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
-
obtainFreshBeanFactory
protected org.springframework.beans.factory.config.ConfigurableListableBeanFactory obtainFreshBeanFactory()Tell the subclass to refresh the internal bean factory.- Returns:
- the fresh BeanFactory instance
- See Also:
-
prepareBeanFactory
protected void prepareBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.- Parameters:
beanFactory- the BeanFactory to configure
-
postProcessBeanFactory
protected void postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Modify the application context's internal bean factory after its standard initialization. The initial definition resources will have been loaded but no post-processors will have run and no derived bean definitions will have been registered, and most importantly, no beans will have been instantiated yet.This template method allows for registering special BeanPostProcessors etc in certain AbstractApplicationContext subclasses.
- Parameters:
beanFactory- the bean factory used by the application context
-
invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Instantiate and invoke all registered BeanFactoryPostProcessor beans, respecting explicit order if given.Must be called before singleton instantiation.
-
registerBeanPostProcessors
protected void registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Instantiate and register all BeanPostProcessor beans, respecting explicit order if given.Must be called before any instantiation of application beans.
-
initMessageSource
protected void initMessageSource()Initialize theMessageSource.Uses parent's
MessageSourceif none defined in this context.- See Also:
-
initApplicationEventMulticaster
protected void initApplicationEventMulticaster()Initialize theApplicationEventMulticaster.Uses
SimpleApplicationEventMulticasterif none defined in the context. -
initLifecycleProcessor
protected void initLifecycleProcessor()Initialize theLifecycleProcessor.Uses
DefaultLifecycleProcessorif none defined in the context.- Since:
- 3.0
- See Also:
-
onRefresh
protected void onRefresh() throws org.springframework.beans.BeansExceptionTemplate method which can be overridden to add context-specific refresh work. Called on initialization of special beans, before instantiation of singletons.This implementation is empty.
- Throws:
org.springframework.beans.BeansException- in case of errors- See Also:
-
registerListeners
protected void registerListeners()Add beans that implement ApplicationListener as listeners. Doesn't affect other listeners, which can be added without being beans. -
finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(org.springframework.beans.factory.config.ConfigurableListableBeanFactory beanFactory) Finish the initialization of this context's bean factory, initializing all remaining singleton beans. -
finishRefresh
protected void finishRefresh()Finish the refresh of this context, invoking the LifecycleProcessor's onRefresh() method and publishing theContextRefreshedEvent. -
cancelRefresh
Cancel this context's refresh attempt, resetting theactiveflag after an exception got thrown.- Parameters:
ex- the exception that led to the cancellation
-
resetCommonCaches
protected void resetCommonCaches()Reset Spring's common reflection metadata caches, in particular theReflectionUtils,AnnotationUtils,ResolvableTypeandCachedIntrospectionResultscaches.- Since:
- 4.2
- See Also:
-
ReflectionUtils.clearCache()AnnotationUtils.clearCache()ResolvableType.clearCache()CachedIntrospectionResults.clearClassLoader(ClassLoader)
-
registerShutdownHook
public void registerShutdownHook()Register a shutdown hook namedSpringContextShutdownHookwith the JVM runtime, closing this context on JVM shutdown unless it has already been closed at that time.Delegates to
doClose()for the actual closing procedure.- Specified by:
registerShutdownHookin interfaceConfigurableApplicationContext- See Also:
-
close
public void close()Close this application context, destroying all beans in its bean factory.Delegates to
doClose()for the actual closing procedure. Also removes a JVM shutdown hook, if registered, as it's not needed anymore.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Specified by:
closein interfaceConfigurableApplicationContext- See Also:
-
doClose
protected void doClose()Actually performs context closing: publishes a ContextClosedEvent and destroys the singletons in the bean factory of this application context.Called by both
close()and a JVM shutdown hook, if any. -
destroyBeans
protected void destroyBeans()Template method for destroying all beans that this context manages. The default implementation destroy all cached singletons in this context, invokingDisposableBean.destroy()and/or the specified "destroy-method".Can be overridden to add context-specific bean destruction steps right before or right after standard singleton destruction, while the context's BeanFactory is still active.
- See Also:
-
getBeanFactory()ConfigurableBeanFactory.destroySingletons()
-
onClose
protected void onClose()Template method which can be overridden to add context-specific shutdown work. The default implementation is empty.Called at the end of
doClose()'s shutdown procedure, after this context's BeanFactory has been closed. If custom shutdown logic needs to execute while the BeanFactory is still active, override thedestroyBeans()method instead. -
isActive
public boolean isActive()Description copied from interface:ConfigurableApplicationContextDetermine whether this application context is active, that is, whether it has been refreshed at least once and has not been closed yet.- Specified by:
isActivein interfaceConfigurableApplicationContext- Returns:
- whether the context is still active
- See Also:
-
assertBeanFactoryActive
protected void assertBeanFactoryActive()Assert that this context's BeanFactory is currently active, throwing anIllegalStateExceptionif it isn't.Invoked by all
BeanFactorydelegation methods that depend on an active context, i.e. in particular all bean accessor methods.The default implementation checks the
'active'status of this context overall. May be overridden for more specific checks, or for a no-op ifgetBeanFactory()itself throws an exception in such a case. -
getBean
- Specified by:
getBeanin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.BeansException
-
getBean
public <T> T getBean(String name, Class<T> requiredType) throws org.springframework.beans.BeansException - Specified by:
getBeanin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.BeansException
-
getBean
- Specified by:
getBeanin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.BeansException
-
getBean
- Specified by:
getBeanin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.BeansException
-
getBean
public <T> T getBean(Class<T> requiredType, Object... args) throws org.springframework.beans.BeansException - Specified by:
getBeanin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.BeansException
-
getBeanProvider
public <T> org.springframework.beans.factory.ObjectProvider<T> getBeanProvider(Class<T> requiredType) - Specified by:
getBeanProviderin interfaceorg.springframework.beans.factory.BeanFactory
-
getBeanProvider
public <T> org.springframework.beans.factory.ObjectProvider<T> getBeanProvider(org.springframework.core.ResolvableType requiredType) - Specified by:
getBeanProviderin interfaceorg.springframework.beans.factory.BeanFactory
-
containsBean
- Specified by:
containsBeanin interfaceorg.springframework.beans.factory.BeanFactory
-
isSingleton
public boolean isSingleton(String name) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
isSingletonin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
isPrototype
public boolean isPrototype(String name) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
isPrototypein interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
isTypeMatch
public boolean isTypeMatch(String name, org.springframework.core.ResolvableType typeToMatch) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
isTypeMatchin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
isTypeMatch
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
isTypeMatchin interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
getType
@Nullable public Class<?> getType(String name) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
getTypein interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
getType
@Nullable public Class<?> getType(String name, boolean allowFactoryBeanInit) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
getTypein interfaceorg.springframework.beans.factory.BeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
getAliases
- Specified by:
getAliasesin interfaceorg.springframework.beans.factory.BeanFactory
-
containsBeanDefinition
- Specified by:
containsBeanDefinitionin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanDefinitionCount
public int getBeanDefinitionCount()- Specified by:
getBeanDefinitionCountin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanDefinitionNames
- Specified by:
getBeanDefinitionNamesin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanProvider
public <T> org.springframework.beans.factory.ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit) - Specified by:
getBeanProviderin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanProvider
public <T> org.springframework.beans.factory.ObjectProvider<T> getBeanProvider(org.springframework.core.ResolvableType requiredType, boolean allowEagerInit) - Specified by:
getBeanProviderin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanNamesForType
- Specified by:
getBeanNamesForTypein interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanNamesForType
public String[] getBeanNamesForType(org.springframework.core.ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) - Specified by:
getBeanNamesForTypein interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanNamesForType
- Specified by:
getBeanNamesForTypein interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeanNamesForType
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) - Specified by:
getBeanNamesForTypein interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeansOfType
public <T> Map<String,T> getBeansOfType(@Nullable Class<T> type) throws org.springframework.beans.BeansException - Specified by:
getBeansOfTypein interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.BeansException
-
getBeansOfType
public <T> Map<String,T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws org.springframework.beans.BeansException - Specified by:
getBeansOfTypein interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.BeansException
-
getBeanNamesForAnnotation
- Specified by:
getBeanNamesForAnnotationin interfaceorg.springframework.beans.factory.ListableBeanFactory
-
getBeansWithAnnotation
public Map<String,Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws org.springframework.beans.BeansException - Specified by:
getBeansWithAnnotationin interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.BeansException
-
findAnnotationOnBean
@Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
findAnnotationOnBeanin interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
findAnnotationOnBean
@Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
findAnnotationOnBeanin interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
findAllAnnotationsOnBean
public <A extends Annotation> Set<A> findAllAnnotationsOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) throws org.springframework.beans.factory.NoSuchBeanDefinitionException - Specified by:
findAllAnnotationsOnBeanin interfaceorg.springframework.beans.factory.ListableBeanFactory- Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException
-
getParentBeanFactory
@Nullable public org.springframework.beans.factory.BeanFactory getParentBeanFactory()- Specified by:
getParentBeanFactoryin interfaceorg.springframework.beans.factory.HierarchicalBeanFactory
-
containsLocalBean
- Specified by:
containsLocalBeanin interfaceorg.springframework.beans.factory.HierarchicalBeanFactory
-
getInternalParentBeanFactory
@Nullable protected org.springframework.beans.factory.BeanFactory getInternalParentBeanFactory()Return the internal bean factory of the parent context if it implements ConfigurableApplicationContext; else, return the parent context itself. -
getMessage
@Nullable public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) Description copied from interface:MessageSourceTry to resolve the message. Return default message if no message was found.- Specified by:
getMessagein interfaceMessageSource- Parameters:
code- the message code to look up, e.g. 'calculator.noRateSet'. MessageSource users are encouraged to base message names on qualified class or package names, avoiding potential conflicts and ensuring maximum clarity.args- an array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}" within a message), ornullif nonedefaultMessage- a default message to return if the lookup failslocale- the locale in which to do the lookup- Returns:
- the resolved message if the lookup was successful, otherwise
the default message passed as a parameter (which may be
null) - See Also:
-
getMessage
public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException Description copied from interface:MessageSourceTry to resolve the message. Treat as an error if the message can't be found.- Specified by:
getMessagein interfaceMessageSource- Parameters:
code- the message code to look up, e.g. 'calculator.noRateSet'. MessageSource users are encouraged to base message names on qualified class or package names, avoiding potential conflicts and ensuring maximum clarity.args- an array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}" within a message), ornullif nonelocale- the locale in which to do the lookup- Returns:
- the resolved message (never
null) - Throws:
NoSuchMessageException- if no corresponding message was found- See Also:
-
getMessage
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException Description copied from interface:MessageSourceTry to resolve the message using all the attributes contained within theMessageSourceResolvableargument that was passed in.NOTE: We must throw a
NoSuchMessageExceptionon this method since at the time of calling this method we aren't able to determine if thedefaultMessageproperty of the resolvable isnullor not.- Specified by:
getMessagein interfaceMessageSource- Parameters:
resolvable- the value object storing attributes required to resolve a message (may include a default message)locale- the locale in which to do the lookup- Returns:
- the resolved message (never
nullsince even aMessageSourceResolvable-provided default message needs to be non-null) - Throws:
NoSuchMessageException- if no corresponding message was found (and no default message was provided by theMessageSourceResolvable)- See Also:
-
getInternalParentMessageSource
Return the internal message source of the parent context if it is an AbstractApplicationContext too; else, return the parent context itself. -
getResources
public org.springframework.core.io.Resource[] getResources(String locationPattern) throws IOException - Specified by:
getResourcesin interfaceorg.springframework.core.io.support.ResourcePatternResolver- Throws:
IOException
-
start
public void start()Description copied from interface:LifecycleStart this component.Should not throw an exception if the component is already running.
In the case of a container, this will propagate the start signal to all components that apply.
-
stop
public void stop()Description copied from interface:LifecycleStop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method. Consider implementingSmartLifecycleand itsstop(Runnable)variant when asynchronous stop behavior is necessary.Note that this stop notification is not guaranteed to come before destruction: On regular shutdown,
Lifecyclebeans will first receive a stop notification before the general destruction callbacks are being propagated; however, on hot refresh during a context's lifetime or on aborted refresh attempts, a given bean's destroy method will be called without any consideration of stop signals upfront.Should not throw an exception if the component is not running (not started yet).
In the case of a container, this will propagate the stop signal to all components that apply.
- Specified by:
stopin interfaceLifecycle- See Also:
-
SmartLifecycle.stop(Runnable)DisposableBean.destroy()
-
isRunning
public boolean isRunning()Description copied from interface:LifecycleCheck whether this component is currently running.In the case of a container, this will return
trueonly if all components that apply are currently running. -
refreshBeanFactory
protected abstract void refreshBeanFactory() throws org.springframework.beans.BeansException, IllegalStateExceptionSubclasses must implement this method to perform the actual configuration load. The method is invoked byrefresh()before any other initialization work.A subclass will either create a new bean factory and hold a reference to it, or return a single BeanFactory instance that it holds. In the latter case, it will usually throw an IllegalStateException if refreshing the context more than once.
- Throws:
org.springframework.beans.BeansException- if initialization of the bean factory failedIllegalStateException- if already initialized and multiple refresh attempts are not supported
-
closeBeanFactory
protected abstract void closeBeanFactory()Subclasses must implement this method to release their internal bean factory. This method gets invoked byclose()after all other shutdown work.Should never throw an exception but rather log shutdown failures.
-
getBeanFactory
public abstract org.springframework.beans.factory.config.ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateExceptionSubclasses must return their internal bean factory here. They should implement the lookup efficiently, so that it can be called repeatedly without a performance penalty.Note: Subclasses should check whether the context is still active before returning the internal bean factory. The internal factory should generally be considered unavailable once the context has been closed.
- Specified by:
getBeanFactoryin interfaceConfigurableApplicationContext- Returns:
- this application context's internal bean factory (never
null) - Throws:
IllegalStateException- if the context does not hold an internal bean factory yet (usually ifrefresh()has never been called) or if the context has been closed already- See Also:
-
toString
Return information about this context.
-