Class AbstractApplicationContext
- All Implemented Interfaces:
Closeable,AutoCloseable,BeanFactory,HierarchicalBeanFactory,ListableBeanFactory,ApplicationContext,ApplicationEventPublisher,ConfigurableApplicationContext,Lifecycle,MessageSource,EnvironmentCapable,ResourceLoader,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:
-
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.core.io.DefaultResourceLoader
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 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(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) Does this bean factory contain a bean definition or externally registered singleton instance with the given name?booleancontainsBeanDefinition(String beanName) Check if this bean factory contains a bean definition with the given name.booleancontainsLocalBean(String name) Return whether the local bean factory contains a bean of the given name, ignoring beans defined in ancestor contexts.protected 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) Find allAnnotationinstances ofannotationTypeon the specified bean, traversing its interfaces and superclasses if no annotation can be found on the given class itself, as well as checking the bean's factory method (if any).<A extends Annotation>
AfindAnnotationOnBean(String beanName, Class<A> annotationType) Find anAnnotationofannotationTypeon the specified bean, traversing its interfaces and superclasses if no annotation can be found on the given class itself, as well as checking the bean's factory method (if any).<A extends Annotation>
AfindAnnotationOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) Find anAnnotationofannotationTypeon the specified bean, traversing its interfaces and superclasses if no annotation can be found on the given class itself, as well as checking the bean's factory method (if any).protected voidFinish 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 aliases for the given bean name, if any.Return the list of statically specified ApplicationListeners.Return a name for the deployed application that this context belongs to.Return theApplicationStartupfor this application context.Return this context's internal bean factory as AutowireCapableBeanFactory, if already available.<T> TReturn the bean instance that uniquely matches the given object type, if any.<T> TReturn an instance, which may be shared or independent, of the specified bean.Return an instance, which may be shared or independent, of the specified bean.<T> TReturn an instance, which may be shared or independent, of the specified bean.Return an instance, which may be shared or independent, of the specified bean.intReturn the number of beans defined in the factory.String[]Return the names of all beans defined in this factory.abstract ConfigurableListableBeanFactorySubclasses must return their internal bean factory here.Return the list of BeanFactoryPostProcessors that will get applied to the internal BeanFactory.String[]getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) Find all names of beans which are annotated with the suppliedAnnotationtype, without creating corresponding bean instances yet.String[]getBeanNamesForType(Class<?> type) Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.String[]getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.String[]Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.String[]getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.<T> ObjectProvider<T>getBeanProvider(Class<T> requiredType) Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.<T> ObjectProvider<T>getBeanProvider(Class<T> requiredType, boolean allowEagerInit) Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.<T> ObjectProvider<T>getBeanProvider(ResolvableType requiredType) Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.<T> ObjectProvider<T>getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.getBeansOfType(Class<T> type) Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.getBeansWithAnnotation(Class<? extends Annotation> annotationType) Find all beans which are annotated with the suppliedAnnotationtype, returning a Map of bean names with corresponding bean instances.Return a friendly name for this context.Return theEnvironmentfor this application context in configurable form, allowing for further customization.getId()Return the unique id of this application context.protected 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).Return the parent bean factory, ornullif there is none.protected ResourcePatternResolverReturn the ResourcePatternResolver to use for resolving location patterns into Resource instances.Resource[]getResources(String locationPattern) Resolve the given location pattern intoResourceobjects.longReturn the timestamp (ms) when this context was first loaded.Class<?>Determine the type of the bean with the given name.Class<?>Determine the type of the bean with the given name.protected voidInitialize theApplicationEventMulticaster.protected voidInitialize theLifecycleProcessor.protected voidInitialize theMessageSource.protected voidReplace any stub property sources with actual instances.protected voidInstantiate 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) Is this bean a prototype? That is, willBeanFactory.getBean(java.lang.String)always return independent instances?booleanCheck whether this component is currently running.booleanisSingleton(String name) Is this bean a shared singleton? That is, willBeanFactory.getBean(java.lang.String)always return the same instance?booleanisTypeMatch(String name, Class<?> typeToMatch) Check whether the bean with the given name matches the specified type.booleanisTypeMatch(String name, ResolvableType typeToMatch) Check whether the bean with the given name matches the specified type.protected 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(ConfigurableListableBeanFactory beanFactory) Modify the application context's internal bean factory after its standard initialization.protected voidprepareBeanFactory(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, 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 voidInstantiate 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(ApplicationStartup applicationStartup) Set theApplicationStartupfor this application context.voidsetDisplayName(String displayName) Set a friendly name for this context.voidsetEnvironment(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
Logger 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
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
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 interfaceEnvironmentCapable
-
createEnvironment
Create and return a newStandardEnvironment.Subclasses may override this method in order to supply a custom
ConfigurableEnvironmentimplementation. -
getAutowireCapableBeanFactory
Return 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
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
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
Description copied from interface:ConfigurableApplicationContextReturn theApplicationStartupfor this application context.- Specified by:
getApplicationStartupin interfaceConfigurableApplicationContext
-
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:
-
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:
-
addBeanFactoryPostProcessor
Description copied from interface:
-