public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext
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 |
---|---|
static java.lang.String |
APPLICATION_EVENT_MULTICASTER_BEAN_NAME
Name of the ApplicationEventMulticaster bean in the factory.
|
static java.lang.String |
LIFECYCLE_PROCESSOR_BEAN_NAME
Name of the LifecycleProcessor bean in the factory.
|
protected Log |
logger
Logger used by this class.
|
static java.lang.String |
MESSAGE_SOURCE_BEAN_NAME
Name of the MessageSource bean in the factory.
|
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 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 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()
Deprecated.
as of Spring Framework 5.0, in favor of
close() |
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.
|
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> ObjectProvider<T> |
getBeanProvider(java.lang.Class<T> requiredType)
Return an 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 an provider for the specified bean, allowing for lazy on-demand retrieval
of instances, including availability and uniqueness options.
|
<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, allowing for further customization. |
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.
|
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.
|
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 reflection metadata caches, in particular the
ReflectionUtils , AnnotationUtils , ResolvableType
and 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.
|
addProtocolResolver, clearResourceCaches, getClassLoader, getProtocolResolvers, getResource, getResourceByPath, getResourceCache, setClassLoader
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
addProtocolResolver
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
public AbstractApplicationContext()
public AbstractApplicationContext(@Nullable 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
)@Nullable 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 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 ConfigurableEnvironment getEnvironment()
Environment
for this application context in configurable
form, allowing for further customization.
If none specified, a default environment will be initialized via
createEnvironment()
.
getEnvironment
in interface ConfigurableApplicationContext
getEnvironment
in interface EnvironmentCapable
protected ConfigurableEnvironment createEnvironment()
StandardEnvironment
.
Subclasses may override this method in order to supply
a custom ConfigurableEnvironment
implementation.
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, @Nullable 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 knownprotected 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(@Nullable ApplicationContext parent)
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 postProcessor)
ConfigurableApplicationContext
addBeanFactoryPostProcessor
in interface ConfigurableApplicationContext
postProcessor
- 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()
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()
ReflectionUtils
, AnnotationUtils
, ResolvableType
and CachedIntrospectionResults
caches.public void registerShutdownHook()
Delegates to doClose()
for the actual closing procedure.
registerShutdownHook
in interface ConfigurableApplicationContext
Runtime.addShutdownHook(java.lang.Thread)
,
close()
,
doClose()
@Deprecated public void destroy()
close()
DisposableBean
implementation (not anymore in 5.0).
The close()
method is the native way to shut down
an ApplicationContext, which this method simply delegates to.
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 superclassNoSuchBeanDefinitionException
- if there is no such bean definitionBeanNotOfRequiredTypeException
- if the bean is not of the required typeBeansException
- if the bean could not be createdpublic 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) throws BeansException
BeanFactory
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
.
getBean
in interface BeanFactory
requiredType
- type the bean must match; can be an interface or superclassNoSuchBeanDefinitionException
- 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 <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.
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
.
getBean
in interface BeanFactory
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)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> ObjectProvider<T> getBeanProvider(java.lang.Class<T> requiredType)
BeanFactory
getBeanProvider
in interface BeanFactory
requiredType
- type the bean must match; can be an interface or superclassBeanFactory.getBeanProvider(ResolvableType)
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType)
BeanFactory
getBeanProvider
in interface BeanFactory
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
use ObjectProvider#toList()
or its lazy streaming/iteration options.ObjectProvider.stream()
,
ObjectProvider.iterator()
,
ObjectProvider#toList()
public 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)
@Nullable 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 generically typed class or interface to matchBeanFactory.isTypeMatch(String, ResolvableType)
,
FactoryBean.getObjectType()
,
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ListableBeanFactory, ResolvableType)
public java.lang.String[] getBeanNamesForType(@Nullable 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(@Nullable 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(@Nullable 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(@Nullable 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 created@Nullable public <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
otherwiseNoSuchBeanDefinitionException
- if there is no bean with the given name@Nullable public 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)
@Nullable protected BeanFactory getInternalParentBeanFactory()
public java.lang.String getMessage(java.lang.String code, @Nullable java.lang.Object[] args, @Nullable 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
- 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),
or null
if none.defaultMessage
- a default message to return if the lookup failslocale
- the locale in which to do the lookupMessageFormat
public java.lang.String getMessage(java.lang.String code, @Nullable 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
- 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),
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
- the value object storing attributes required to resolve a messagelocale
- the locale in which to do the lookupNoSuchMessageException
- if the message wasn't foundMessageFormat
@Nullable protected 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, 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.
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