public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean
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 "applicationEventMulticaster" bean
of type ApplicationEventMulticaster
in the context; otherwise, a default multicaster of type
SimpleApplicationEventMulticaster
will be used.
Implements resource loading through 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 overwritten in a subclass.
refreshBeanFactory()
,
getBeanFactory()
,
BeanFactoryPostProcessor
,
BeanPostProcessor
,
ApplicationEventMulticaster
,
ApplicationListener
,
MessageSource
DefaultResourceLoader.ClassPathContextResource
Modifier and Type | Field and Description |
---|---|
private java.util.concurrent.atomic.AtomicBoolean |
active
Flag that indicates whether this context is currently active
|
static java.lang.String |
APPLICATION_EVENT_MULTICASTER_BEAN_NAME
Name of the ApplicationEventMulticaster bean in the factory.
|
private ApplicationEventMulticaster |
applicationEventMulticaster
Helper class used in event publishing
|
private java.util.Set<ApplicationListener<?>> |
applicationListeners
Statically specified listeners
|
private java.util.List<BeanFactoryPostProcessor> |
beanFactoryPostProcessors
BeanFactoryPostProcessors to apply on refresh
|
private java.util.concurrent.atomic.AtomicBoolean |
closed
Flag that indicates whether this context has been closed already
|
private java.lang.String |
displayName
Display name
|
private java.util.Set<ApplicationEvent> |
earlyApplicationEvents
ApplicationEvents published early
|
private ConfigurableEnvironment |
environment
Environment used by this context
|
private java.lang.String |
id
Unique id for this context, if any
|
static java.lang.String |
LIFECYCLE_PROCESSOR_BEAN_NAME
Name of the LifecycleProcessor bean in the factory.
|
private LifecycleProcessor |
lifecycleProcessor
LifecycleProcessor for managing the lifecycle of beans within this context
|
protected Log |
logger
Logger used by this class.
|
static java.lang.String |
MESSAGE_SOURCE_BEAN_NAME
Name of the MessageSource bean in the factory.
|
private MessageSource |
messageSource
MessageSource we delegate our implementation of this interface to
|
private ApplicationContext |
parent
Parent context
|
private ResourcePatternResolver |
resourcePatternResolver
ResourcePatternResolver used by this context
|
private java.lang.Thread |
shutdownHook
Reference to the JVM shutdown hook, if registered
|
private long |
startupDate
System time in milliseconds when this context started
|
private java.lang.Object |
startupShutdownMonitor
Synchronization monitor for the "refresh" and "destroy"
|
CONFIG_LOCATION_DELIMITERS, CONVERSION_SERVICE_BEAN_NAME, ENVIRONMENT_BEAN_NAME, LOAD_TIME_WEAVER_BEAN_NAME, SYSTEM_ENVIRONMENT_BEAN_NAME, SYSTEM_PROPERTIES_BEAN_NAME
FACTORY_BEAN_PREFIX
CLASSPATH_ALL_URL_PREFIX
CLASSPATH_URL_PREFIX
Constructor and Description |
---|
AbstractApplicationContext()
Create a new AbstractApplicationContext with no parent.
|
AbstractApplicationContext(ApplicationContext parent)
Create a new AbstractApplicationContext with the given parent context.
|
Modifier and Type | Method and Description |
---|---|
void |
addApplicationListener(ApplicationListener<?> listener)
Add a new ApplicationListener that will be notified on context events
such as context refresh and context shutdown.
|
void |
addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor)
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 void |
assertBeanFactoryActive()
Assert that this context's BeanFactory is currently active,
throwing an
IllegalStateException if it isn't. |
protected void |
cancelRefresh(BeansException ex)
Cancel this context's refresh attempt, resetting the
active flag
after an exception got thrown. |
void |
close()
Close this application context, destroying all beans in its bean factory.
|
protected abstract void |
closeBeanFactory()
Subclasses must implement this method to release their internal bean factory.
|
boolean |
containsBean(java.lang.String name)
Does this bean factory contain a bean definition or externally registered singleton
instance with the given name?
|
boolean |
containsBeanDefinition(java.lang.String beanName)
Check if this bean factory contains a bean definition with the given name.
|
boolean |
containsLocalBean(java.lang.String name)
Return whether the local bean factory contains a bean of the given name,
ignoring beans defined in ancestor contexts.
|
protected ConfigurableEnvironment |
createEnvironment()
Create and return a new
StandardEnvironment . |
void |
destroy()
DisposableBean callback for destruction of this instance.
|
protected void |
destroyBeans()
Template method for destroying all beans that this context manages.
|
protected void |
doClose()
Actually performs context closing: publishes a ContextClosedEvent and
destroys the singletons in the bean factory of this application context.
|
<A extends java.lang.annotation.Annotation> |
findAnnotationOnBean(java.lang.String beanName,
java.lang.Class<A> annotationType)
Find an
Annotation of annotationType on the specified
bean, traversing its interfaces and super classes if no annotation can be
found on the given class itself. |
protected void |
finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)
Finish the initialization of this context's bean factory,
initializing all remaining singleton beans.
|
protected void |
finishRefresh()
Finish the refresh of this context, invoking the LifecycleProcessor's
onRefresh() method and publishing the
ContextRefreshedEvent . |
java.lang.String[] |
getAliases(java.lang.String name)
Return the aliases for the given bean name, if any.
|
(package private) ApplicationEventMulticaster |
getApplicationEventMulticaster()
Return the internal ApplicationEventMulticaster used by the context.
|
java.util.Collection<ApplicationListener<?>> |
getApplicationListeners()
Return the list of statically specified ApplicationListeners.
|
java.lang.String |
getApplicationName()
Return a name for the deployed application that this context belongs to.
|
AutowireCapableBeanFactory |
getAutowireCapableBeanFactory()
Return this context's internal bean factory as AutowireCapableBeanFactory,
if already available.
|
<T> T |
getBean(java.lang.Class<T> requiredType)
Return the bean instance that uniquely matches the given object type, if any.
|
<T> T |
getBean(java.lang.Class<T> requiredType,
java.lang.Object... args)
Return an instance, which may be shared or independent, of the specified bean.
|
java.lang.Object |
getBean(java.lang.String name)
Return an instance, which may be shared or independent, of the specified bean.
|
<T> T |
getBean(java.lang.String name,
java.lang.Class<T> requiredType)
Return an instance, which may be shared or independent, of the specified bean.
|
java.lang.Object |
getBean(java.lang.String name,
java.lang.Object... args)
Return an instance, which may be shared or independent, of the specified bean.
|
int |
getBeanDefinitionCount()
Return the number of beans defined in the factory.
|
java.lang.String[] |
getBeanDefinitionNames()
Return the names of all beans defined in this factory.
|
abstract ConfigurableListableBeanFactory |
getBeanFactory()
Subclasses must return their internal bean factory here.
|
java.util.List<BeanFactoryPostProcessor> |
getBeanFactoryPostProcessors()
Return the list of BeanFactoryPostProcessors that will get applied
to the internal BeanFactory.
|
java.lang.String[] |
getBeanNamesForAnnotation(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType)
Find all names of beans whose
Class has the supplied Annotation
type, without creating any bean instances yet. |
java.lang.String[] |
getBeanNamesForType(java.lang.Class<?> type)
Return the names of beans matching the given type (including subclasses),
judging from either bean definitions or the value of
getObjectType
in the case of FactoryBeans. |
java.lang.String[] |
getBeanNamesForType(java.lang.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 of
getObjectType
in the case of FactoryBeans. |
java.lang.String[] |
getBeanNamesForType(ResolvableType type)
Return the names of beans matching the given type (including subclasses),
judging from either bean definitions or the value of
getObjectType
in the case of FactoryBeans. |
<T> java.util.Map<java.lang.String,T> |
getBeansOfType(java.lang.Class<T> type)
Return the bean instances that match the given object type (including
subclasses), judging from either bean definitions or the value of
getObjectType in the case of FactoryBeans. |
<T> java.util.Map<java.lang.String,T> |
getBeansOfType(java.lang.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 of
getObjectType in the case of FactoryBeans. |
java.util.Map<java.lang.String,java.lang.Object> |
getBeansWithAnnotation(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType)
Find all beans whose
Class has the supplied Annotation type,
returning a Map of bean names with corresponding bean instances. |
java.lang.String |
getDisplayName()
Return a friendly name for this context.
|
ConfigurableEnvironment |
getEnvironment()
Return the Environment for this application context in configurable form.
|
java.lang.String |
getId()
Return the unique id of this application context.
|
protected BeanFactory |
getInternalParentBeanFactory()
Return the internal bean factory of the parent context if it implements
ConfigurableApplicationContext; else, return the parent context itself.
|
protected MessageSource |
getInternalParentMessageSource()
Return the internal message source of the parent context if it is an
AbstractApplicationContext too; else, return the parent context itself.
|
(package private) LifecycleProcessor |
getLifecycleProcessor()
Return the internal LifecycleProcessor used by the context.
|
java.lang.String |
getMessage(MessageSourceResolvable resolvable,
java.util.Locale locale)
Try to resolve the message using all the attributes contained within the
MessageSourceResolvable argument that was passed in. |
java.lang.String |
getMessage(java.lang.String code,
java.lang.Object[] args,
java.util.Locale locale)
Try to resolve the message.
|
java.lang.String |
getMessage(java.lang.String code,
java.lang.Object[] args,
java.lang.String defaultMessage,
java.util.Locale locale)
Try to resolve the message.
|
private MessageSource |
getMessageSource()
Return the internal MessageSource used by the context.
|
ApplicationContext |
getParent()
Return the parent context, or
null if there is no parent
(that is, this context is the root of the context hierarchy). |
BeanFactory |
getParentBeanFactory()
Return the parent bean factory, or
null if there is none. |
protected ResourcePatternResolver |
getResourcePatternResolver()
Return the ResourcePatternResolver to use for resolving location patterns
into Resource instances.
|
Resource[] |
getResources(java.lang.String locationPattern)
Resolve the given location pattern into Resource objects.
|
long |
getStartupDate()
Return the timestamp (ms) when this context was first loaded.
|
java.lang.Class<?> |
getType(java.lang.String name)
Determine the type of the bean with the given name.
|
protected void |
initApplicationEventMulticaster()
Initialize the ApplicationEventMulticaster.
|
protected void |
initLifecycleProcessor()
Initialize the LifecycleProcessor.
|
protected void |
initMessageSource()
Initialize the MessageSource.
|
protected void |
initPropertySources()
Replace any stub property sources with actual instances.
|
protected void |
invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)
Instantiate and invoke all registered BeanFactoryPostProcessor beans,
respecting explicit order if given.
|
boolean |
isActive()
Determine whether this application context is active, that is,
whether it has been refreshed at least once and has not been closed yet.
|
boolean |
isPrototype(java.lang.String name)
Is this bean a prototype? That is, will
BeanFactory.getBean(java.lang.String) always return
independent instances? |
boolean |
isRunning()
Check whether this component is currently running.
|
boolean |
isSingleton(java.lang.String name)
Is this bean a shared singleton? That is, will
BeanFactory.getBean(java.lang.String) always
return the same instance? |
boolean |
isTypeMatch(java.lang.String name,
java.lang.Class<?> typeToMatch)
Check whether the bean with the given name matches the specified type.
|
boolean |
isTypeMatch(java.lang.String name,
ResolvableType typeToMatch)
Check whether the bean with the given name matches the specified type.
|
protected ConfigurableListableBeanFactory |
obtainFreshBeanFactory()
Tell the subclass to refresh the internal bean factory.
|
protected void |
onClose()
Template method which can be overridden to add context-specific shutdown work.
|
protected void |
onRefresh()
Template method which can be overridden to add context-specific refresh work.
|
protected void |
postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
Modify the application context's internal bean factory after its standard
initialization.
|
protected void |
prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
Configure the factory's standard context characteristics,
such as the context's ClassLoader and post-processors.
|
protected void |
prepareRefresh()
Prepare this context for refreshing, setting its startup date and
active flag as well as performing any initialization of property sources.
|
void |
publishEvent(ApplicationEvent event)
Publish the given event to all listeners.
|
void |
publishEvent(java.lang.Object event)
Publish the given event to all listeners.
|
protected void |
publishEvent(java.lang.Object event,
ResolvableType eventType)
Publish the given event to all listeners.
|
void |
refresh()
Load or refresh the persistent representation of the configuration,
which might an XML file, properties file, or relational database schema.
|
protected abstract void |
refreshBeanFactory()
Subclasses must implement this method to perform the actual configuration load.
|
protected void |
registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)
Instantiate and invoke all registered BeanPostProcessor beans,
respecting explicit order if given.
|
protected void |
registerListeners()
Add beans that implement ApplicationListener as listeners.
|
void |
registerShutdownHook()
Register a shutdown hook with the JVM runtime, closing this context
on JVM shutdown unless it has already been closed at that time.
|
protected void |
resetCommonCaches()
Reset Spring's common core caches, in particular the
ResolvableType
and the CachedIntrospectionResults caches. |
void |
setDisplayName(java.lang.String displayName)
Set a friendly name for this context.
|
void |
setEnvironment(ConfigurableEnvironment environment)
Set the
Environment for this application context. |
void |
setId(java.lang.String id)
Set the unique id of this application context.
|
void |
setParent(ApplicationContext parent)
Set the parent of this application context.
|
void |
start()
Start this component.
|
void |
stop()
Stop this component, typically in a synchronous fashion, such that the component is
fully stopped upon return of this method.
|
java.lang.String |
toString()
Return information about this context.
|
getClassLoader, getResource, getResourceByPath, setClassLoader
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
getClassLoader, getResource
public static final java.lang.String MESSAGE_SOURCE_BEAN_NAME
MessageSource
,
Constant Field Valuespublic static final java.lang.String LIFECYCLE_PROCESSOR_BEAN_NAME
public static final java.lang.String APPLICATION_EVENT_MULTICASTER_BEAN_NAME
protected final Log logger
private java.lang.String id
private java.lang.String displayName
private ApplicationContext parent
private ConfigurableEnvironment environment
private final java.util.List<BeanFactoryPostProcessor> beanFactoryPostProcessors
private long startupDate
private final java.util.concurrent.atomic.AtomicBoolean active
private final java.util.concurrent.atomic.AtomicBoolean closed
private final java.lang.Object startupShutdownMonitor
private java.lang.Thread shutdownHook
private ResourcePatternResolver resourcePatternResolver
private LifecycleProcessor lifecycleProcessor
private MessageSource messageSource
private ApplicationEventMulticaster applicationEventMulticaster
private final java.util.Set<ApplicationListener<?>> applicationListeners
private java.util.Set<ApplicationEvent> earlyApplicationEvents
public AbstractApplicationContext()
public AbstractApplicationContext(ApplicationContext parent)
parent
- the parent contextpublic void setId(java.lang.String id)
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.
setId
in interface ConfigurableApplicationContext
id
- the unique id of the contextpublic java.lang.String getId()
ApplicationContext
getId
in interface ApplicationContext
null
if nonepublic java.lang.String getApplicationName()
ApplicationContext
getApplicationName
in interface ApplicationContext
public void setDisplayName(java.lang.String displayName)
Default is the object id of the context instance.
public java.lang.String getDisplayName()
getDisplayName
in interface ApplicationContext
null
)public ApplicationContext getParent()
null
if there is no parent
(that is, this context is the root of the context hierarchy).getParent
in interface ApplicationContext
null
if there is no parentpublic ConfigurableEnvironment getEnvironment()
If null
, a new environment will be initialized via
createEnvironment()
.
getEnvironment
in interface ConfigurableApplicationContext
getEnvironment
in interface EnvironmentCapable
public void setEnvironment(ConfigurableEnvironment environment)
Environment
for this application context.
Default value is determined by createEnvironment()
. Replacing the
default with this method is one option but configuration through getEnvironment()
should also be considered. In either case, such modifications
should be performed before refresh()
.
setEnvironment
in interface ConfigurableApplicationContext
environment
- the new environmentcreateEnvironment()
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws java.lang.IllegalStateException
getAutowireCapableBeanFactory
in interface ApplicationContext
java.lang.IllegalStateException
- if the context does not support the
AutowireCapableBeanFactory
interface, or does not hold an
autowire-capable bean factory yet (e.g. if refresh()
has
never been called), or if the context has been closed alreadygetBeanFactory()
public long getStartupDate()
getStartupDate
in interface ApplicationContext
public void publishEvent(ApplicationEvent event)
Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannot publish events.
publishEvent
in interface ApplicationEventPublisher
event
- the event to publish (may be application-specific or a
standard framework event)RequestHandledEvent
public void publishEvent(java.lang.Object event)
Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannot publish events.
publishEvent
in interface ApplicationEventPublisher
event
- the event to publish (may be an ApplicationEvent
or a payload object to be turned into a PayloadApplicationEvent
)PayloadApplicationEvent
protected void publishEvent(java.lang.Object event, ResolvableType eventType)
event
- the event to publish (may be an ApplicationEvent
or a payload object to be turned into a PayloadApplicationEvent
)eventType
- the resolved event type, if knownApplicationEventMulticaster getApplicationEventMulticaster() throws java.lang.IllegalStateException
null
)java.lang.IllegalStateException
- if the context has not been initialized yetLifecycleProcessor getLifecycleProcessor() throws java.lang.IllegalStateException
null
)java.lang.IllegalStateException
- if the context has not been initialized yetprotected ResourcePatternResolver getResourcePatternResolver()
PathMatchingResourcePatternResolver
,
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 getResources
method instead, which
will delegate to the ResourcePatternResolver.
getResources(java.lang.String)
,
PathMatchingResourcePatternResolver
public void setParent(ApplicationContext parent)
Note that the parent shouldn't be changed: It should only be set outside a constructor if it isn't available when an object of this class is created, for example in case of WebApplicationContext setup.
The parent environment is
merged with
this (child) application context environment if the parent is non-null
and
its environment is an instance of ConfigurableEnvironment
.
setParent
in interface ConfigurableApplicationContext
parent
- the parent contextConfigurableEnvironment.merge(ConfigurableEnvironment)
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor)
ConfigurableApplicationContext
addBeanFactoryPostProcessor
in interface ConfigurableApplicationContext
beanFactoryPostProcessor
- the factory processor to registerpublic java.util.List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors()
public void addApplicationListener(ApplicationListener<?> listener)
ConfigurableApplicationContext
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.
addApplicationListener
in interface ConfigurableApplicationContext
listener
- the ApplicationListener to registerContextRefreshedEvent
,
ContextClosedEvent
public java.util.Collection<ApplicationListener<?>> getApplicationListeners()
protected ConfigurableEnvironment createEnvironment()
StandardEnvironment
.
Subclasses may override this method in order to supply
a custom ConfigurableEnvironment
implementation.
public void refresh() throws BeansException, java.lang.IllegalStateException
ConfigurableApplicationContext
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 that method, either all or no singletons at all should be instantiated.
refresh
in interface ConfigurableApplicationContext
BeansException
- if the bean factory could not be initializedjava.lang.IllegalStateException
- if already initialized and multiple refresh
attempts are not supportedprotected void prepareRefresh()
protected void initPropertySources()
Replace any stub property sources with actual instances.
protected ConfigurableListableBeanFactory obtainFreshBeanFactory()
refreshBeanFactory()
,
getBeanFactory()
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
beanFactory
- the BeanFactory to configureprotected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
beanFactory
- the bean factory used by the application contextprotected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)
Must be called before singleton instantiation.
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)
Must be called before any instantiation of application beans.
protected void initMessageSource()
protected void initApplicationEventMulticaster()
SimpleApplicationEventMulticaster
protected void initLifecycleProcessor()
DefaultLifecycleProcessor
protected void onRefresh() throws BeansException
This implementation is empty.
BeansException
- in case of errorsrefresh()
protected void registerListeners()
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)
protected void finishRefresh()
ContextRefreshedEvent
.protected void cancelRefresh(BeansException ex)
active
flag
after an exception got thrown.ex
- the exception that led to the cancellationprotected void resetCommonCaches()
ResolvableType
and the CachedIntrospectionResults
caches.ResolvableType.clearCache()
,
CachedIntrospectionResults.clearClassLoader(ClassLoader)
public void registerShutdownHook()
Delegates to doClose()
for the actual closing procedure.
registerShutdownHook
in interface ConfigurableApplicationContext
Runtime.addShutdownHook(java.lang.Thread)
,
close()
,
doClose()
public void destroy()
The close
method is the native way to
shut down an ApplicationContext.
destroy
in interface DisposableBean
close()
,
SingletonBeanFactoryLocator
public void close()
Delegates to doClose()
for the actual closing procedure.
Also removes a JVM shutdown hook, if registered, as it's not needed anymore.
close
in interface java.io.Closeable
close
in interface java.lang.AutoCloseable
close
in interface ConfigurableApplicationContext
doClose()
,
registerShutdownHook()
protected void doClose()
Called by both close()
and a JVM shutdown hook, if any.
ContextClosedEvent
,
destroyBeans()
,
close()
,
registerShutdownHook()
protected void destroyBeans()
DisposableBean.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.
protected void onClose()
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
the destroyBeans()
method instead.
public boolean isActive()
ConfigurableApplicationContext
isActive
in interface ConfigurableApplicationContext
ConfigurableApplicationContext.refresh()
,
ConfigurableApplicationContext.close()
,
ConfigurableApplicationContext.getBeanFactory()
protected void assertBeanFactoryActive()
IllegalStateException
if it isn't.
Invoked by all BeanFactory
delegation 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 if getBeanFactory()
itself throws an exception in such a case.
public java.lang.Object getBean(java.lang.String name) throws BeansException
BeanFactory
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.
getBean
in interface BeanFactory
name
- the name of the bean to retrieveNoSuchBeanDefinitionException
- if there is no bean definition
with the specified nameBeansException
- if the bean could not be obtainedpublic <T> T getBean(java.lang.String name, java.lang.Class<T> requiredType) throws BeansException
BeanFactory
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 with BeanFactory.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.
getBean
in interface BeanFactory
name
- the name of the bean to retrieverequiredType
- type the bean must match. Can be an interface or superclass
of the actual class, or null
for any match. For example, if the value
is Object.class
, this method will succeed whatever the class of the
returned instance.NoSuchBeanDefinitionException
- if there is no such bean definitionBeanNotOfRequiredTypeException
- if the bean is not of the required typeBeansException
- if the bean could not be createdpublic <T> T getBean(java.lang.Class<T> requiredType) throws BeansException
BeanFactory
getBean
in interface BeanFactory
requiredType
- type the bean must match; can be an interface or superclass.
null
is disallowed.
This method goes into ListableBeanFactory
by-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,
use ListableBeanFactory
and/or BeanFactoryUtils
.
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 createdListableBeanFactory
public java.lang.Object getBean(java.lang.String name, java.lang.Object... args) throws BeansException
BeanFactory
Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.
getBean
in interface BeanFactory
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)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 createdpublic <T> T getBean(java.lang.Class<T> requiredType, java.lang.Object... args) throws BeansException
BeanFactory
Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.
getBean
in interface BeanFactory
requiredType
- type the bean must match; can be an interface or superclass.
null
is disallowed.
This method goes into ListableBeanFactory
by-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,
use ListableBeanFactory
and/or BeanFactoryUtils
.
args
- 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)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 createdpublic boolean containsBean(java.lang.String name)
BeanFactory
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 true
whether the named bean definition is concrete
or abstract, lazy or eager, in scope or not. Therefore, note that a true
return value from this method does not necessarily indicate that BeanFactory.getBean(java.lang.String)
will be able to obtain an instance for the same name.
containsBean
in interface BeanFactory
name
- the name of the bean to querypublic boolean isSingleton(java.lang.String name) throws NoSuchBeanDefinitionException
BeanFactory
BeanFactory.getBean(java.lang.String)
always
return the same instance?
Note: This method returning false
does not clearly indicate
independent instances. It indicates non-singleton instances, which may correspond
to a scoped bean as well. Use the BeanFactory.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.
isSingleton
in interface BeanFactory
name
- the name of the bean to queryNoSuchBeanDefinitionException
- if there is no bean with the given nameBeanFactory.getBean(java.lang.String)
,
BeanFactory.isPrototype(java.lang.String)
public boolean isPrototype(java.lang.String name) throws NoSuchBeanDefinitionException
BeanFactory
BeanFactory.getBean(java.lang.String)
always return
independent instances?
Note: This method returning false
does not clearly indicate
a singleton object. It indicates non-independent instances, which may correspond
to a scoped bean as well. Use the BeanFactory.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.
isPrototype
in interface BeanFactory
name
- the name of the bean to queryNoSuchBeanDefinitionException
- if there is no bean with the given nameBeanFactory.getBean(java.lang.String)
,
BeanFactory.isSingleton(java.lang.String)
public boolean isTypeMatch(java.lang.String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException
BeanFactory
BeanFactory.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.
isTypeMatch
in interface BeanFactory
name
- the name of the bean to querytypeToMatch
- the type to match against (as a ResolvableType
)true
if the bean type matches,
false
if it doesn't match or cannot be determined yetNoSuchBeanDefinitionException
- if there is no bean with the given nameBeanFactory.getBean(java.lang.String)
,
BeanFactory.getType(java.lang.String)
public boolean isTypeMatch(java.lang.String name, java.lang.Class<?> typeToMatch) throws NoSuchBeanDefinitionException
BeanFactory
BeanFactory.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.
isTypeMatch
in interface BeanFactory
name
- the name of the bean to querytypeToMatch
- the type to match against (as a Class
)true
if the bean type matches,
false
if it doesn't match or cannot be determined yetNoSuchBeanDefinitionException
- if there is no bean with the given nameBeanFactory.getBean(java.lang.String)
,
BeanFactory.getType(java.lang.String)
public java.lang.Class<?> getType(java.lang.String name) throws NoSuchBeanDefinitionException
BeanFactory
BeanFactory.getBean(java.lang.String)
would return for the given name.
For a FactoryBean
, return the type of object that the FactoryBean creates,
as exposed by FactoryBean.getObjectType()
.
Translates aliases back to the corresponding canonical bean name. Will ask the parent factory if the bean cannot be found in this factory instance.
getType
in interface BeanFactory
name
- the name of the bean to querynull
if not determinableNoSuchBeanDefinitionException
- if there is no bean with the given nameBeanFactory.getBean(java.lang.String)
,
BeanFactory.isTypeMatch(java.lang.String, org.springframework.core.ResolvableType)
public java.lang.String[] getAliases(java.lang.String name)
BeanFactory
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.
getAliases
in interface BeanFactory
name
- the bean name to check for aliasesBeanFactory.getBean(java.lang.String)
public boolean containsBeanDefinition(java.lang.String beanName)
ListableBeanFactory
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.
containsBeanDefinition
in interface ListableBeanFactory
beanName
- the name of the bean to look forBeanFactory.containsBean(java.lang.String)
public int getBeanDefinitionCount()
ListableBeanFactory
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.
getBeanDefinitionCount
in interface ListableBeanFactory
public java.lang.String[] getBeanDefinitionNames()
ListableBeanFactory
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.
getBeanDefinitionNames
in interface ListableBeanFactory
public java.lang.String[] getBeanNamesForType(ResolvableType type)
ListableBeanFactory
getObjectType
in 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' beanNamesForTypeIncludingAncestors
to include beans in ancestor factories too.
Note: Does not ignore singleton beans that have been registered by other means than bean definitions.
This version of getBeanNamesForType
matches all kinds of beans,
be it singletons, prototypes, or FactoryBeans. In most implementations, the
result will be the same as for getBeanNamesForType(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.
getBeanNamesForType
in interface ListableBeanFactory
type
- the class or interface to match, or null
for all bean namesFactoryBean.getObjectType()
,
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ListableBeanFactory, ResolvableType)
public java.lang.String[] getBeanNamesForType(java.lang.Class<?> type)
ListableBeanFactory
getObjectType
in 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' beanNamesForTypeIncludingAncestors
to include beans in ancestor factories too.
Note: Does not ignore singleton beans that have been registered by other means than bean definitions.
This version of getBeanNamesForType
matches all kinds of beans,
be it singletons, prototypes, or FactoryBeans. In most implementations, the
result will be the same as for getBeanNamesForType(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.
getBeanNamesForType
in interface ListableBeanFactory
type
- the class or interface to match, or null
for all bean namesFactoryBean.getObjectType()
,
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class)
public java.lang.String[] getBeanNamesForType(java.lang.Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
ListableBeanFactory
getObjectType
in 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' beanNamesForTypeIncludingAncestors
to include beans in ancestor factories too.
Note: Does not ignore singleton beans that have been registered by other means than bean definitions.
Bean names returned by this method should always return bean names in the order of definition in the backend configuration, as far as possible.
getBeanNamesForType
in interface ListableBeanFactory
type
- the class or interface to match, or null
for all bean namesincludeNonSingletons
- whether to include prototype or scoped beans too
or just singletons (also applies to FactoryBeans)allowEagerInit
- whether to initialize 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.FactoryBean.getObjectType()
,
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
public <T> java.util.Map<java.lang.String,T> getBeansOfType(java.lang.Class<T> type) throws BeansException
ListableBeanFactory
getObjectType
in 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' beansOfTypeIncludingAncestors
to include beans in ancestor factories too.
Note: Does not ignore singleton beans that have been registered by other means than bean definitions.
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.
getBeansOfType
in interface ListableBeanFactory
type
- the class or interface to match, or null
for all concrete beansBeansException
- if a bean could not be createdFactoryBean.getObjectType()
,
BeanFactoryUtils.beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
public <T> java.util.Map<java.lang.String,T> getBeansOfType(java.lang.Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException
ListableBeanFactory
getObjectType
in 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' beansOfTypeIncludingAncestors
to include beans in ancestor factories too.
Note: Does not ignore singleton beans that have been registered by other means than bean definitions.
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.
getBeansOfType
in interface ListableBeanFactory
type
- the class or interface to match, or null
for all concrete beansincludeNonSingletons
- whether to include prototype or scoped beans too
or just singletons (also applies to FactoryBeans)allowEagerInit
- whether to initialize 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.BeansException
- if a bean could not be createdFactoryBean.getObjectType()
,
BeanFactoryUtils.beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
public java.lang.String[] getBeanNamesForAnnotation(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType)
ListableBeanFactory
Class
has the supplied Annotation
type, without creating any bean instances yet.getBeanNamesForAnnotation
in interface ListableBeanFactory
annotationType
- the type of annotation to look forpublic java.util.Map<java.lang.String,java.lang.Object> getBeansWithAnnotation(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType) throws BeansException
ListableBeanFactory
Class
has the supplied Annotation
type,
returning a Map of bean names with corresponding bean instances.getBeansWithAnnotation
in interface ListableBeanFactory
annotationType
- the type of annotation to look forBeansException
- if a bean could not be createdpublic <A extends java.lang.annotation.Annotation> A findAnnotationOnBean(java.lang.String beanName, java.lang.Class<A> annotationType) throws NoSuchBeanDefinitionException
ListableBeanFactory
Annotation
of annotationType
on the specified
bean, traversing its interfaces and super classes if no annotation can be
found on the given class itself.findAnnotationOnBean
in interface ListableBeanFactory
beanName
- the name of the bean to look for annotations onannotationType
- the annotation class to look fornull
NoSuchBeanDefinitionException
- if there is no bean with the given namepublic BeanFactory getParentBeanFactory()
HierarchicalBeanFactory
null
if there is none.getParentBeanFactory
in interface HierarchicalBeanFactory
public boolean containsLocalBean(java.lang.String name)
HierarchicalBeanFactory
This is an alternative to containsBean
, ignoring a bean
of the given name from an ancestor bean factory.
containsLocalBean
in interface HierarchicalBeanFactory
name
- the name of the bean to queryBeanFactory.containsBean(java.lang.String)
protected BeanFactory getInternalParentBeanFactory()
public java.lang.String getMessage(java.lang.String code, java.lang.Object[] args, java.lang.String defaultMessage, java.util.Locale locale)
MessageSource
getMessage
in interface MessageSource
code
- the code to lookup up, such as 'calculator.noRateSet'. Users of
this class are encouraged to base message names on the relevant fully
qualified class name, thus avoiding conflict and ensuring maximum clarity.args
- array of arguments that will be filled in for params within
the message (params look like "{0}", "{1,date}", "{2,time}" within a message),
or null
if none.defaultMessage
- String to return if the lookup failslocale
- the Locale in which to do the lookupMessageFormat
public java.lang.String getMessage(java.lang.String code, java.lang.Object[] args, java.util.Locale locale) throws NoSuchMessageException
MessageSource
getMessage
in interface MessageSource
code
- the code to lookup up, such as 'calculator.noRateSet'args
- Array of arguments that will be filled in for params within
the message (params look like "{0}", "{1,date}", "{2,time}" within a message),
or null
if none.locale
- the Locale in which to do the lookupNoSuchMessageException
- if the message wasn't foundMessageFormat
public java.lang.String getMessage(MessageSourceResolvable resolvable, java.util.Locale locale) throws NoSuchMessageException
MessageSource
MessageSourceResolvable
argument that was passed in.
NOTE: We must throw a NoSuchMessageException
on this method
since at the time of calling this method we aren't able to determine if the
defaultMessage
property of the resolvable is null or not.
getMessage
in interface MessageSource
resolvable
- value object storing attributes required to properly resolve a messagelocale
- the Locale in which to do the lookupNoSuchMessageException
- if the message wasn't foundMessageFormat
private MessageSource getMessageSource() throws java.lang.IllegalStateException
null
)java.lang.IllegalStateException
- if the context has not been initialized yetprotected MessageSource getInternalParentMessageSource()
public Resource[] getResources(java.lang.String locationPattern) throws java.io.IOException
ResourcePatternResolver
Overlapping resource entries that point to the same physical resource should be avoided, as far as possible. The result should have set semantics.
getResources
in interface ResourcePatternResolver
locationPattern
- the location pattern to resolvejava.io.IOException
- in case of I/O errorspublic void start()
Lifecycle
Should not throw an exception if the component is already running.
In the case of a container, this will propagate the start signal to all components that apply.
start
in interface Lifecycle
SmartLifecycle.isAutoStartup()
public void stop()
Lifecycle
SmartLifecycle
and its stop(Runnable)
variant when asynchronous stop behavior is necessary.
Note that this stop notification is not guaranteed to come before destruction: On
regular shutdown, Lifecycle
beans 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, only destroy methods will be called.
Should not throw an exception if the component isn't started yet.
In the case of a container, this will propagate the stop signal to all components that apply.
stop
in interface Lifecycle
SmartLifecycle.stop(Runnable)
,
DisposableBean.destroy()
public boolean isRunning()
Lifecycle
In the case of a container, this will return true
only if all
components that apply are currently running.
protected abstract void refreshBeanFactory() throws BeansException, java.lang.IllegalStateException
refresh()
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.
BeansException
- if initialization of the bean factory failedjava.lang.IllegalStateException
- if already initialized and multiple refresh
attempts are not supportedprotected abstract void closeBeanFactory()
close()
after all other shutdown work.
Should never throw an exception but rather log shutdown failures.
public abstract ConfigurableListableBeanFactory getBeanFactory() throws java.lang.IllegalStateException
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.
getBeanFactory
in interface ConfigurableApplicationContext
null
)java.lang.IllegalStateException
- if the context does not hold an internal bean factory yet
(usually if refresh()
has never been called) or if the context has been
closed alreadyrefreshBeanFactory()
,
closeBeanFactory()
public java.lang.String toString()
toString
in class java.lang.Object