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,
for example, "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_PREFIX, FACTORY_BEAN_PREFIX_CHARFields inherited from interface org.springframework.context.ConfigurableApplicationContext
APPLICATION_STARTUP_BEAN_NAME, BOOTSTRAP_EXECUTOR_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.voidClear all resource caches in this resource loader.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.booleanisClosed()Return whether this context has been closed already, that is, whetherConfigurableApplicationContext.close()has been called on an active context in order to initiate its shutdown.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, 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 (for example, 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: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
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:
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.
-
obtainFreshBeanFactory
Tell the subclass to refresh the internal bean factory.- Returns:
- the fresh BeanFactory instance
- See Also:
-
prepareBeanFactory
Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.- Parameters:
beanFactory- the BeanFactory to configure
-
postProcessBeanFactory
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
Instantiate and invoke all registered BeanFactoryPostProcessor beans, respecting explicit order if given.Must be called before singleton instantiation.
-
registerBeanPostProcessors
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
Template 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:
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
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. -
clearResourceCaches
public void clearResourceCaches()Description copied from class:DefaultResourceLoaderClear all resource caches in this resource loader.- Overrides:
clearResourceCachesin classDefaultResourceLoader- See Also:
-
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.
-
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. -
isClosed
public boolean isClosed()Description copied from interface:ConfigurableApplicationContextReturn whether this context has been closed already, that is, whetherConfigurableApplicationContext.close()has been called on an active context in order to initiate its shutdown.Note: This does not indicate whether context shutdown has completed. Use
ConfigurableApplicationContext.isActive()for differentiating between those scenarios: a context becomes inactive once it has been fully shut down and the originalclose()call has returned.- Specified by:
isClosedin interfaceConfigurableApplicationContext
-
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
Description copied from interface:BeanFactoryReturn an instance, which may be shared or independent, of the specified bean.This method allows a Spring BeanFactory to be used as a replacement for the Singleton or Prototype design pattern. Callers may retain references to returned objects in the case of Singleton beans.
Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
getBeanin interfaceBeanFactory- Parameters:
name- the name of the bean to retrieve- Returns:
- an instance of the bean.
Note that the return value will never be
nullbut possibly a stub fornullreturned from a factory method, to be checked viaequals(null). Consider usingBeanFactory.getBeanProvider(Class)for resolving optional dependencies. - Throws:
NoSuchBeanDefinitionException- if there is no bean with the specified nameBeansException- if the bean could not be obtained
-
getBean
Description copied from interface:BeanFactoryReturn an instance, which may be shared or independent, of the specified bean.Behaves the same as
BeanFactory.getBean(String), but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. This means that ClassCastException can't be thrown on casting the result correctly, as can happen withBeanFactory.getBean(String).Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
getBeanin interfaceBeanFactory- Parameters:
name- the name of the bean to retrieverequiredType- type the bean must match; can be an interface or superclass- Returns:
- an instance of the bean.
Note that the return value will never be
null. In case of a stub fornullfrom a factory method having been resolved for the requested bean, aBeanNotOfRequiredTypeExceptionagainst the NullBean stub will be raised. Consider usingBeanFactory.getBeanProvider(Class)for resolving optional dependencies. - Throws:
NoSuchBeanDefinitionException- if there is no such bean definitionBeanNotOfRequiredTypeException- if the bean is not of the required typeBeansException- if the bean could not be created
-
getBean
Description copied from interface:BeanFactoryReturn an instance, which may be shared or independent, of the specified bean.Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition. Note that the provided arguments need to match a specific candidate constructor / factory method in the order of declared parameters.
- Specified by:
getBeanin interfaceBeanFactory- Parameters:
name- the name of the bean to retrieveargs- arguments to use when creating a bean instance using explicit arguments (only applied when creating a new instance as opposed to retrieving an existing one)- Returns:
- an instance of the bean
- Throws:
NoSuchBeanDefinitionException- if there is no such bean definitionBeanDefinitionStoreException- if arguments have been given but the affected bean isn't a prototypeBeansException- if the bean could not be created
-
getBean
Description copied from interface:BeanFactoryReturn the bean instance that uniquely matches the given object type, if any.This method goes into
ListableBeanFactoryby-type lookup territory but may also be translated into a conventional by-name lookup based on the name of the given type. For more extensive retrieval operations across sets of beans, useListableBeanFactoryand/orBeanFactoryUtils.- Specified by:
getBeanin interfaceBeanFactory- Parameters:
requiredType- type the bean must match; can be an interface or superclass- Returns:
- an instance of the single bean matching the required type
- Throws:
NoSuchBeanDefinitionException- if no bean of the given type was foundNoUniqueBeanDefinitionException- if more than one bean of the given type was foundBeansException- if the bean could not be created- See Also:
-
getBean
Description copied from interface:BeanFactoryReturn an instance, which may be shared or independent, of the specified bean.Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition. Note that the provided arguments need to match a specific candidate constructor / factory method in the order of declared parameters.
This method goes into
ListableBeanFactoryby-type lookup territory but may also be translated into a conventional by-name lookup based on the name of the given type. For more extensive retrieval operations across sets of beans, useListableBeanFactoryand/orBeanFactoryUtils.- Specified by:
getBeanin interfaceBeanFactory- Parameters:
requiredType- type the bean must match; can be an interface or superclassargs- arguments to use when creating a bean instance using explicit arguments (only applied when creating a new instance as opposed to retrieving an existing one)- Returns:
- an instance of the bean
- Throws:
NoSuchBeanDefinitionException- if there is no such bean definitionBeanDefinitionStoreException- if arguments have been given but the affected bean isn't a prototypeBeansException- if the bean could not be created
-
getBeanProvider
Description copied from interface:BeanFactoryReturn a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.For matching a generic type, consider
BeanFactory.getBeanProvider(ResolvableType).- Specified by:
getBeanProviderin interfaceBeanFactory- Parameters:
requiredType- type the bean must match; can be an interface or superclass- Returns:
- a corresponding provider handle
- See Also:
-
getBeanProvider
Description copied from interface:BeanFactoryReturn a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options. This variant allows for specifying a generic type to match, similar to reflective injection points with generic type declarations in method/constructor parameters.Note that collections of beans are not supported here, in contrast to reflective injection points. For programmatically retrieving a list of beans matching a specific type, specify the actual bean type as an argument here and subsequently use
ObjectProvider.orderedStream()or its lazy streaming/iteration options.Also, generics matching is strict here, as per the Java assignment rules. For lenient fallback matching with unchecked semantics (similar to the 'unchecked' Java compiler warning), consider calling
BeanFactory.getBeanProvider(Class)with the raw type as a second step if no full generic match isavailablewith this variant.- Specified by:
getBeanProviderin interfaceBeanFactory- Parameters:
requiredType- type the bean must match; can be a generic type declaration- Returns:
- a corresponding provider handle
- See Also:
-
containsBean
Description copied from interface:BeanFactoryDoes this bean factory contain a bean definition or externally registered singleton instance with the given name?If the given name is an alias, it will be translated back to the corresponding canonical bean name.
If this factory is hierarchical, will ask any parent factory if the bean cannot be found in this factory instance.
If a bean definition or singleton instance matching the given name is found, this method will return
truewhether the named bean definition is concrete or abstract, lazy or eager, in scope or not. Therefore, note that atruereturn value from this method does not necessarily indicate thatBeanFactory.getBean(java.lang.String)will be able to obtain an instance for the same name.- Specified by:
containsBeanin interfaceBeanFactory- Parameters:
name- the name of the bean to query- Returns:
- whether a bean with the given name is present
-
isSingleton
Description copied from interface:BeanFactoryIs this bean a shared singleton? That is, willBeanFactory.getBean(java.lang.String)always return the same instance?Note: This method returning
falsedoes not clearly indicate independent instances. It indicates non-singleton instances, which may correspond to a scoped bean as well. Use theBeanFactory.isPrototype(java.lang.String)operation to explicitly check for independent instances.Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
isSingletonin interfaceBeanFactory- Parameters:
name- the name of the bean to query- Returns:
- whether this bean corresponds to a singleton instance
- Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
isPrototype
Description copied from interface:BeanFactoryIs this bean a prototype? That is, willBeanFactory.getBean(java.lang.String)always return independent instances?Note: This method returning
falsedoes not clearly indicate a singleton object. It indicates non-independent instances, which may correspond to a scoped bean as well. Use theBeanFactory.isSingleton(java.lang.String)operation to explicitly check for a shared singleton instance.Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
isPrototypein interfaceBeanFactory- Parameters:
name- the name of the bean to query- Returns:
- whether this bean will always deliver independent instances
- Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
isTypeMatch
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException Description copied from interface:BeanFactoryCheck whether the bean with the given name matches the specified type. More specifically, check whether aBeanFactory.getBean(java.lang.String)call for the given name would return an object that is assignable to the specified target type.Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
isTypeMatchin interfaceBeanFactory- Parameters:
name- the name of the bean to querytypeToMatch- the type to match against (as aResolvableType)- Returns:
trueif the bean type matches,falseif it doesn't match or cannot be determined yet- Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
isTypeMatch
Description copied from interface:BeanFactoryCheck whether the bean with the given name matches the specified type. More specifically, check whether aBeanFactory.getBean(java.lang.String)call for the given name would return an object that is assignable to the specified target type.Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
isTypeMatchin interfaceBeanFactory- Parameters:
name- the name of the bean to querytypeToMatch- the type to match against (as aClass)- Returns:
trueif the bean type matches,falseif it doesn't match or cannot be determined yet- Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
getType
Description copied from interface:BeanFactoryDetermine the type of the bean with the given name. More specifically, determine the type of object thatBeanFactory.getBean(java.lang.String)would return for the given name.For a
FactoryBean, return the type of object that the FactoryBean creates, as exposed byFactoryBean.getObjectType(). This may lead to the initialization of a previously uninitializedFactoryBean(seeBeanFactory.getType(String, boolean)).Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
getTypein interfaceBeanFactory- Parameters:
name- the name of the bean to query- Returns:
- the type of the bean, or
nullif not determinable - Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
getType
@Nullable public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException Description copied from interface:BeanFactoryDetermine the type of the bean with the given name. More specifically, determine the type of object thatBeanFactory.getBean(java.lang.String)would return for the given name.For a
FactoryBean, return the type of object that the FactoryBean creates, as exposed byFactoryBean.getObjectType(). Depending on theallowFactoryBeanInitflag, this may lead to the initialization of a previously uninitializedFactoryBeanif no early type information is available.Translates aliases back to the corresponding canonical bean name.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
getTypein interfaceBeanFactory- Parameters:
name- the name of the bean to queryallowFactoryBeanInit- whether aFactoryBeanmay get initialized just for the purpose of determining its object type- Returns:
- the type of the bean, or
nullif not determinable - Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
getAliases
Description copied from interface:BeanFactoryReturn the aliases for the given bean name, if any.All of those aliases point to the same bean when used in a
BeanFactory.getBean(java.lang.String)call.If the given name is an alias, the corresponding original bean name and other aliases (if any) will be returned, with the original bean name being the first element in the array.
Will ask the parent factory if the bean cannot be found in this factory instance.
- Specified by:
getAliasesin interfaceBeanFactory- Parameters:
name- the bean name to check for aliases- Returns:
- the aliases, or an empty array if none
- See Also:
-
containsBeanDefinition
Description copied from interface:ListableBeanFactoryCheck if this bean factory contains a bean definition with the given name.Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.
- Specified by:
containsBeanDefinitionin interfaceListableBeanFactory- Parameters:
beanName- the name of the bean to look for- Returns:
- if this bean factory contains a bean definition with the given name
- See Also:
-
getBeanDefinitionCount
public int getBeanDefinitionCount()Description copied from interface:ListableBeanFactoryReturn the number of beans defined in the factory.Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.
- Specified by:
getBeanDefinitionCountin interfaceListableBeanFactory- Returns:
- the number of beans defined in the factory
-
getBeanDefinitionNames
Description copied from interface:ListableBeanFactoryReturn the names of all beans defined in this factory.Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.
- Specified by:
getBeanDefinitionNamesin interfaceListableBeanFactory- Returns:
- the names of all beans defined in this factory, or an empty array if none defined
-
getBeanProvider
Description copied from interface:ListableBeanFactoryReturn a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.- Specified by:
getBeanProviderin interfaceListableBeanFactory- Parameters:
requiredType- type the bean must match; can be an interface or superclassallowEagerInit- whether stream access may introspect lazy-init singletons and objects created by FactoryBeans - or by factory methods with a "factory-bean" reference - for the type check. Note that FactoryBeans need to be eagerly initialized to determine their type: So be aware that passing in "true" for this flag will initialize FactoryBeans and "factory-bean" references. Only actually necessary initialization for type checking purposes will be performed; constructor and method invocations will still be avoided as far as possible.- Returns:
- a corresponding provider handle
- See Also:
-
getBeanProvider
Description copied from interface:ListableBeanFactoryReturn a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.- Specified by:
getBeanProviderin interfaceListableBeanFactory- Parameters:
requiredType- type the bean must match; can be a generic type declaration. Note that collection types are not supported here, in contrast to reflective injection points. For programmatically retrieving a list of beans matching a specific type, specify the actual bean type as an argument here and subsequently useObjectProvider.orderedStream()or its lazy streaming/iteration options.allowEagerInit- whether stream access may introspect lazy-init singletons and objects created by FactoryBeans - or by factory methods with a "factory-bean" reference - for the type check. Note that FactoryBeans need to be eagerly initialized to determine their type: So be aware that passing in "true" for this flag will initialize FactoryBeans and "factory-bean" references. Only actually necessary initialization for type checking purposes will be performed; constructor and method invocations will still be avoided as far as possible.- Returns:
- a corresponding provider handle
- See Also:
-
getBeanNamesForType
Description copied from interface:ListableBeanFactoryReturn the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well.
Does consider objects created by FactoryBeans, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type.
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beanNamesForTypeIncludingAncestorsto include beans in ancestor factories too.This version of
getBeanNamesForTypematches all kinds of beans, be it singletons, prototypes, or FactoryBeans. In most implementations, the result will be the same as forgetBeanNamesForType(type, true, true).Bean names returned by this method should always return bean names in the order of definition in the backend configuration, as far as possible.
- Specified by:
getBeanNamesForTypein interfaceListableBeanFactory- Parameters:
type- the generically typed class or interface to match- Returns:
- the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none
- See Also:
-
getBeanNamesForType
public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) Description copied from interface:ListableBeanFactoryReturn the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well.
Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked (which doesn't require initialization of each FactoryBean).
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beanNamesForTypeIncludingAncestorsto include beans in ancestor factories too.Bean names returned by this method should always return bean names in the order of definition in the backend configuration, as far as possible.
- Specified by:
getBeanNamesForTypein interfaceListableBeanFactory- Parameters:
type- the generically typed class or interface to matchincludeNonSingletons- whether to include prototype or scoped beans too or just singletons (also applies to FactoryBeans)allowEagerInit- whether to introspect lazy-init singletons and objects created by FactoryBeans - or by factory methods with a "factory-bean" reference - for the type check. Note that FactoryBeans need to be eagerly initialized to determine their type: So be aware that passing in "true" for this flag will initialize FactoryBeans and "factory-bean" references. Only actually necessary initialization for type checking purposes will be performed; constructor and method invocations will still be avoided as far as possible.- Returns:
- the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none
- See Also:
-
getBeanNamesForType
Description copied from interface:ListableBeanFactoryReturn the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well.
Does consider objects created by FactoryBeans, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type.
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beanNamesForTypeIncludingAncestorsto include beans in ancestor factories too.This version of
getBeanNamesForTypematches all kinds of beans, be it singletons, prototypes, or FactoryBeans. In most implementations, the result will be the same as forgetBeanNamesForType(type, true, true).Bean names returned by this method should always return bean names in the order of definition in the backend configuration, as far as possible.
- Specified by:
getBeanNamesForTypein interfaceListableBeanFactory- Parameters:
type- the class or interface to match, ornullfor all bean names- Returns:
- the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none
- See Also:
-
getBeanNamesForType
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) Description copied from interface:ListableBeanFactoryReturn the names of beans matching the given type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well.
Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked (which doesn't require initialization of each FactoryBean).
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beanNamesForTypeIncludingAncestorsto include beans in ancestor factories too.Bean names returned by this method should always return bean names in the order of definition in the backend configuration, as far as possible.
- Specified by:
getBeanNamesForTypein interfaceListableBeanFactory- Parameters:
type- the class or interface to match, ornullfor all bean namesincludeNonSingletons- whether to include prototype or scoped beans too or just singletons (also applies to FactoryBeans)allowEagerInit- whether to introspect lazy-init singletons and objects created by FactoryBeans - or by factory methods with a "factory-bean" reference - for the type check. Note that FactoryBeans need to be eagerly initialized to determine their type: So be aware that passing in "true" for this flag will initialize FactoryBeans and "factory-bean" references. Only actually necessary initialization for type checking purposes will be performed; constructor and method invocations will still be avoided as far as possible.- Returns:
- the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none
- See Also:
-
getBeansOfType
Description copied from interface:ListableBeanFactoryReturn the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well. Also, it suppresses exceptions for beans that are currently in creation in a circular reference scenario: typically, references back to the caller of this method.
Does consider objects created by FactoryBeans, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type.
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beansOfTypeIncludingAncestorsto include beans in ancestor factories too.This version of getBeansOfType matches all kinds of beans, be it singletons, prototypes, or FactoryBeans. In most implementations, the result will be the same as for
getBeansOfType(type, true, true).The Map returned by this method should always return bean names and corresponding bean instances in the order of definition in the backend configuration, as far as possible.
Consider
ListableBeanFactory.getBeanNamesForType(Class)with selectiveBeanFactory.getBean(java.lang.String)calls for specific bean names in preference to this Map-based retrieval method. Aside from lazy instantiation benefits, this also avoids any exception suppression.- Specified by:
getBeansOfTypein interfaceListableBeanFactory- Parameters:
type- the class or interface to match, ornullfor all concrete beans- Returns:
- a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values
- Throws:
BeansException- if a bean could not be created- See Also:
-
getBeansOfType
public <T> Map<String,T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException Description copied from interface:ListableBeanFactoryReturn the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value ofgetObjectTypein the case of FactoryBeans.NOTE: This method introspects top-level beans only. It does not check nested beans which might match the specified type as well. Also, it suppresses exceptions for beans that are currently in creation in a circular reference scenario: typically, references back to the caller of this method.
Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, which means that FactoryBeans will get initialized. If the object created by the FactoryBean doesn't match, the raw FactoryBean itself will be matched against the type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked (which doesn't require initialization of each FactoryBean).
Does not consider any hierarchy this factory may participate in. Use BeanFactoryUtils'
beansOfTypeIncludingAncestorsto include beans in ancestor factories too.The Map returned by this method should always return bean names and corresponding bean instances in the order of definition in the backend configuration, as far as possible.
Consider
ListableBeanFactory.getBeanNamesForType(Class)with selectiveBeanFactory.getBean(java.lang.String)calls for specific bean names in preference to this Map-based retrieval method. Aside from lazy instantiation benefits, this also avoids any exception suppression.- Specified by:
getBeansOfTypein interfaceListableBeanFactory- Parameters:
type- the class or interface to match, ornullfor all concrete beansincludeNonSingletons- whether to include prototype or scoped beans too or just singletons (also applies to FactoryBeans)allowEagerInit- whether to introspect lazy-init singletons and objects created by FactoryBeans - or by factory methods with a "factory-bean" reference - for the type check. Note that FactoryBeans need to be eagerly initialized to determine their type: So be aware that passing in "true" for this flag will initialize FactoryBeans and "factory-bean" references. Only actually necessary initialization for type checking purposes will be performed; constructor and method invocations will still be avoided as far as possible.- Returns:
- a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values
- Throws:
BeansException- if a bean could not be created- See Also:
-
getBeanNamesForAnnotation
Description copied from interface:ListableBeanFactoryFind all names of beans which are annotated with the suppliedAnnotationtype, without creating corresponding bean instances yet.Note that this method considers objects created by FactoryBeans, which means that FactoryBeans will get initialized in order to determine their object type.
- Specified by:
getBeanNamesForAnnotationin interfaceListableBeanFactory- Parameters:
annotationType- the type of annotation to look for (at class, interface or factory method level of the specified bean)- Returns:
- the names of all matching beans
- See Also:
-
getBeansWithAnnotation
public Map<String,Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException Description copied from interface:ListableBeanFactoryFind all beans which are annotated with the suppliedAnnotationtype, returning a Map of bean names with corresponding bean instances.Note that this method considers objects created by FactoryBeans, which means that FactoryBeans will get initialized in order to determine their object type.
- Specified by:
getBeansWithAnnotationin interfaceListableBeanFactory- Parameters:
annotationType- the type of annotation to look for (at class, interface or factory method level of the specified bean)- Returns:
- a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values
- Throws:
BeansException- if a bean could not be created- See Also:
-
findAnnotationOnBean
@Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException Description copied from interface:ListableBeanFactoryFind 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).- Specified by:
findAnnotationOnBeanin interfaceListableBeanFactory- Parameters:
beanName- the name of the bean to look for annotations onannotationType- the type of annotation to look for (at class, interface or factory method level of the specified bean)- Returns:
- the annotation of the given type if found, or
nullotherwise - Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
findAnnotationOnBean
@Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException Description copied from interface:ListableBeanFactoryFind 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).- Specified by:
findAnnotationOnBeanin interfaceListableBeanFactory- Parameters:
beanName- the name of the bean to look for annotations onannotationType- the type of annotation to look for (at class, interface or factory method level of the specified bean)allowFactoryBeanInit- whether aFactoryBeanmay get initialized just for the purpose of determining its object type- Returns:
- the annotation of the given type if found, or
nullotherwise - Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
findAllAnnotationsOnBean
public <A extends Annotation> Set<A> findAllAnnotationsOnBean(String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException Description copied from interface:ListableBeanFactoryFind 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).- Specified by:
findAllAnnotationsOnBeanin interfaceListableBeanFactory- Parameters:
beanName- the name of the bean to look for annotations onannotationType- the type of annotation to look for (at class, interface or factory method level of the specified bean)allowFactoryBeanInit- whether aFactoryBeanmay get initialized just for the purpose of determining its object type- Returns:
- the set of annotations of the given type found (potentially empty)
- Throws:
NoSuchBeanDefinitionException- if there is no bean with the given name- See Also:
-
getParentBeanFactory
Description copied from interface:HierarchicalBeanFactoryReturn the parent bean factory, ornullif there is none.- Specified by:
getParentBeanFactoryin interfaceHierarchicalBeanFactory
-
containsLocalBean
Description copied from interface:HierarchicalBeanFactoryReturn whether the local bean factory contains a bean of the given name, ignoring beans defined in ancestor contexts.This is an alternative to
containsBean, ignoring a bean of the given name from an ancestor bean factory.- Specified by:
containsLocalBeanin interfaceHierarchicalBeanFactory- Parameters:
name- the name of the bean to query- Returns:
- whether a bean with the given name is defined in the local factory
- See Also:
-
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, @Nullable 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, for example, '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, @Nullable 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, for example, '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, @Nullable 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
Description copied from interface:ResourcePatternResolverResolve the given location pattern intoResourceobjects.Overlapping resource entries that point to the same physical resource should be avoided, as far as possible. The result should have set semantics.
- Specified by:
getResourcesin interfaceResourcePatternResolver- Parameters:
locationPattern- the location pattern to resolve- Returns:
- the corresponding
Resourceobjects - Throws:
IOException- in case of I/O errors
-
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 a hard start signal to all components that apply, even to non-auto-startup components.
-
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.
-
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
Subclasses 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:
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
Subclasses 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.
-