public abstract class

AbstractApplicationContext

extends DefaultResourceLoader
implements DisposableBean ConfigurableApplicationContext
java.lang.Object
   ↳ org.springframework.core.io.DefaultResourceLoader
     ↳ org.springframework.context.support.AbstractApplicationContext
Known Direct Subclasses
Known Indirect Subclasses

Class Overview

Abstract implementation of the 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 getResourceByPath(String) method is overwritten in a subclass.

Summary

Constants
String APPLICATION_EVENT_MULTICASTER_BEAN_NAME Name of the ApplicationEventMulticaster bean in the factory.
String LIFECYCLE_PROCESSOR_BEAN_NAME Name of the LifecycleProcessor bean in the factory.
String MESSAGE_SOURCE_BEAN_NAME Name of the MessageSource bean in the factory.
[Expand]
Inherited Constants
From interface org.springframework.beans.factory.BeanFactory
From interface org.springframework.context.ConfigurableApplicationContext
From interface org.springframework.core.io.ResourceLoader
From interface org.springframework.core.io.support.ResourcePatternResolver
Fields
protected final Log logger Logger used by this class.
Public Constructors
AbstractApplicationContext()
Create a new AbstractApplicationContext with no parent.
AbstractApplicationContext(ApplicationContext parent)
Create a new AbstractApplicationContext with the given parent context.
Public Methods
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.
void close()
Close this application context, destroying all beans in its bean factory.
boolean containsBean(String name)
Does this bean factory contain a bean with the given name? More specifically, is getBean(Class) able to obtain a bean instance for the given name?

Translates aliases back to the corresponding canonical bean name.

boolean containsBeanDefinition(String beanName)
Check if this bean factory contains a bean definition with the given name.
boolean containsLocalBean(String name)
Return whether the local bean factory contains a bean of the given name, ignoring beans defined in ancestor contexts.
void destroy()
DisposableBean callback for destruction of this instance.
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
Find a Annotation of annotationType on the specified bean, traversing its interfaces and super classes if no annotation can be found on the given class itself.
String[] getAliases(String name)
Return the aliases for the given bean name, if any.
Collection<ApplicationListener<?>> getApplicationListeners()
Return the list of statically specified ApplicationListeners.
AutowireCapableBeanFactory getAutowireCapableBeanFactory()
Return this context's internal bean factory as AutowireCapableBeanFactory, if already available.
<T> T getBean(Class<T> requiredType)
Return the bean instance that uniquely matches the given object type, if any.
Object getBean(String name, Object... args)
Return an instance, which may be shared or independent, of the specified bean.
<T> T getBean(String name, Class<T> requiredType)
Return an instance, which may be shared or independent, of the specified bean.
Object getBean(String name)
Return an instance, which may be shared or independent, of the specified bean.
int getBeanDefinitionCount()
Return the number of beans defined in the factory.
String[] getBeanDefinitionNames()
Return the names of all beans defined in this factory.
abstract ConfigurableListableBeanFactory getBeanFactory()
Subclasses must return their internal bean factory here.
List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors()
Return the list of BeanFactoryPostProcessors that will get applied to the internal BeanFactory.
String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
String[] getBeanNamesForType(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.
<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
<T> Map<String, T> getBeansOfType(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.
Map<StringObject> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
Find all beans whose Class has the supplied Annotation type.
String getDisplayName()
Return a friendly name for this context.
ConfigurableEnvironment getEnvironment()
Return the Environment for this application context in configurable form.
String getId()
Return the unique id of this application context.
String getMessage(MessageSourceResolvable resolvable, Locale locale)
Try to resolve the message using all the attributes contained within the MessageSourceResolvable argument that was passed in.
String getMessage(String code, Object[] args, Locale locale)
Try to resolve the message.
String getMessage(String code, Object[] args, String defaultMessage, 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.
Resource[] getResources(String locationPattern)
Resolve the given location pattern into Resource objects.
long getStartupDate()
Return the timestamp (ms) when this context was first loaded.
Class<?> getType(String name)
Determine the type of the bean with the given name.
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(String name)
Is this bean a prototype? That is, will getBean(Class) always return independent instances?

Note: This method returning false does not clearly indicate a singleton object.

boolean isRunning()
Check whether this component is currently running.
boolean isSingleton(String name)
Is this bean a shared singleton? That is, will getBean(Class) always return the same instance?

Note: This method returning false does not clearly indicate independent instances.

boolean isTypeMatch(String name, Class<?> targetType)
Check whether the bean with the given name matches the specified type.
void publishEvent(ApplicationEvent event)
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.
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.
void setDisplayName(String displayName)
Set a friendly name for this context.
void setEnvironment(ConfigurableEnvironment environment)
Set the Environment for this application context.

Default value is determined by createEnvironment().

void setId(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.
String toString()
Return information about this context.
Protected Methods
void addListener(ApplicationListener<?> listener)
This method is deprecated. as of Spring 3.0, in favor of addApplicationListener(ApplicationListener)
void cancelRefresh(BeansException ex)
Cancel this context's refresh attempt, resetting the active flag after an exception got thrown.
abstract void closeBeanFactory()
Subclasses must implement this method to release their internal bean factory.
ConfigurableEnvironment createEnvironment()
Create and return a new DefaultEnvironment.
void destroyBeans()
Template method for destroying all beans that this context manages.
void doClose()
Actually performs context closing: publishes a ContextClosedEvent and destroys the singletons in the bean factory of this application context.
void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)
Finish the initialization of this context's bean factory, initializing all remaining singleton beans.
void finishRefresh()
Finish the refresh of this context, invoking the LifecycleProcessor's onRefresh() method and publishing the ContextRefreshedEvent.
BeanFactory getInternalParentBeanFactory()
Return the internal bean factory of the parent context if it implements ConfigurableApplicationContext; else, return the parent context itself.
MessageSource getInternalParentMessageSource()
Return the internal message source of the parent context if it is an AbstractApplicationContext too; else, return the parent context itself.
ResourcePatternResolver getResourcePatternResolver()
Return the ResourcePatternResolver to use for resolving location patterns into Resource instances.
void initApplicationEventMulticaster()
Initialize the ApplicationEventMulticaster.
void initLifecycleProcessor()
Initialize the LifecycleProcessor.
void initMessageSource()
Initialize the MessageSource.
void initPropertySources()

Replace any stub property sources with actual instances.

void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)
Instantiate and invoke all registered BeanFactoryPostProcessor beans, respecting explicit order if given.
ConfigurableListableBeanFactory obtainFreshBeanFactory()
Tell the subclass to refresh the internal bean factory.
void onClose()
Template method which can be overridden to add context-specific shutdown work.
void onRefresh()
Template method which can be overridden to add context-specific refresh work.
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
Modify the application context's internal bean factory after its standard initialization.
void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.
void prepareRefresh()
Prepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources.
abstract void refreshBeanFactory()
Subclasses must implement this method to perform the actual configuration load.
void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)
Instantiate and invoke all registered BeanPostProcessor beans, respecting explicit order if given.
void registerListeners()
Add beans that implement ApplicationListener as listeners.
[Expand]
Inherited Methods
From class org.springframework.core.io.DefaultResourceLoader
From class java.lang.Object
From interface org.springframework.beans.factory.BeanFactory
From interface org.springframework.beans.factory.DisposableBean
From interface org.springframework.beans.factory.HierarchicalBeanFactory
From interface org.springframework.beans.factory.ListableBeanFactory
From interface org.springframework.context.ApplicationContext
From interface org.springframework.context.ApplicationEventPublisher
From interface org.springframework.context.ConfigurableApplicationContext
From interface org.springframework.context.Lifecycle
From interface org.springframework.context.MessageSource
From interface org.springframework.core.env.EnvironmentCapable
From interface org.springframework.core.io.ResourceLoader
From interface org.springframework.core.io.support.ResourcePatternResolver

Constants

public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME

Name of the ApplicationEventMulticaster bean in the factory. If none is supplied, a default SimpleApplicationEventMulticaster is used.

Constant Value: "applicationEventMulticaster"

public static final String LIFECYCLE_PROCESSOR_BEAN_NAME

Name of the LifecycleProcessor bean in the factory. If none is supplied, a DefaultLifecycleProcessor is used.

Constant Value: "lifecycleProcessor"

public static final String MESSAGE_SOURCE_BEAN_NAME

Name of the MessageSource bean in the factory. If none is supplied, message resolution is delegated to the parent.

See Also
Constant Value: "messageSource"

Fields

protected final Log logger

Logger used by this class. Available to subclasses.

Public Constructors

public AbstractApplicationContext ()

Create a new AbstractApplicationContext with no parent.

public AbstractApplicationContext (ApplicationContext parent)

Create a new AbstractApplicationContext with the given parent context.

Parameters
parent the parent context

Public Methods

public void addApplicationListener (ApplicationListener<?> listener)

Add a new ApplicationListener that will be notified on context events such as context refresh and context shutdown.

Note that any ApplicationListener registered here will be applied on refresh if the context is not active yet, or on the fly with the current event multicaster in case of a context that is already active.

Parameters
listener the ApplicationListener to register

public 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. To be invoked during context configuration.

Parameters
beanFactoryPostProcessor the factory processor to register

public void close ()

Close this application context, destroying all beans in its bean factory.

Delegates to doClose() for the actual closing procedure. Also removes a JVM shutdown hook, if registered, as it's not needed anymore.

public boolean containsBean (String name)

Does this bean factory contain a bean with the given name? More specifically, is getBean(Class) able to obtain a bean instance for the given name?

Translates aliases back to the corresponding canonical bean name. Will ask the parent factory if the bean cannot be found in this factory instance.

Parameters
name the name of the bean to query
Returns
  • whether a bean with the given name is defined

public boolean containsBeanDefinition (String beanName)

Check if this bean factory contains a bean definition with the given name.

Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.

Parameters
beanName the name of the bean to look for
Returns
  • if this bean factory contains a bean definition with the given name

public boolean containsLocalBean (String name)

Return whether the local bean factory contains a bean of the given name, ignoring beans defined in ancestor contexts.

This is an alternative to containsBean, ignoring a bean of the given name from an ancestor bean factory.

Parameters
name the name of the bean to query
Returns
  • whether a bean with the given name is defined in the local factory

public void destroy ()

DisposableBean callback for destruction of this instance. Only called when the ApplicationContext itself is running as a bean in another BeanFactory or ApplicationContext, which is rather unusual.

The close method is the native way to shut down an ApplicationContext.

public A findAnnotationOnBean (String beanName, Class<A> annotationType)

Find a Annotation of annotationType on the specified bean, traversing its interfaces and super classes if no annotation can be found on the given class itself.

Parameters
beanName the name of the bean to look for annotations on
annotationType the annotation class to look for
Returns
  • the annotation of the given type found, or null

public String[] getAliases (String name)

Return the aliases for the given bean name, if any. All of those aliases point to the same bean when used in a getBean(Class) 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.

Parameters
name the bean name to check for aliases
Returns
  • the aliases, or an empty array if none

public Collection<ApplicationListener<?>> getApplicationListeners ()

Return the list of statically specified ApplicationListeners.

public AutowireCapableBeanFactory getAutowireCapableBeanFactory ()

Return this context's internal bean factory as AutowireCapableBeanFactory, if already available.

Returns
  • the AutowireCapableBeanFactory for this context
See Also

public T getBean (Class<T> requiredType)

Return the bean instance that uniquely matches the given object type, if any.

Parameters
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.

Returns
  • an instance of the single bean matching the required type

public Object getBean (String name, Object... args)

Return an instance, which may be shared or independent, of the specified bean.

Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.

Parameters
name the name of the bean to retrieve
args arguments to use if creating a prototype using explicit arguments to a static factory method. It is invalid to use a non-null args value in any other case.
Returns
  • an instance of the bean

public T getBean (String name, Class<T> requiredType)

Return an instance, which may be shared or independent, of the specified bean.

Behaves the same as 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 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.

Parameters
name the name of the bean to retrieve
requiredType 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.
Returns
  • an instance of the bean

public Object getBean (String name)

Return an instance, which may be shared or independent, of the specified bean.

This method allows a Spring BeanFactory to be used as a replacement for the Singleton or Prototype design pattern. Callers may retain references to returned objects in the case of Singleton beans.

Translates aliases back to the corresponding canonical bean name. Will ask the parent factory if the bean cannot be found in this factory instance.

Parameters
name the name of the bean to retrieve
Returns
  • an instance of the bean

public int getBeanDefinitionCount ()

Return the number of beans defined in the factory.

Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.

Returns
  • the number of beans defined in the factory

public String[] getBeanDefinitionNames ()

Return the names of all beans defined in this factory.

Does not consider any hierarchy this factory may participate in, and ignores any singleton beans that have been registered by other means than bean definitions.

Returns
  • the names of all beans defined in this factory, or an empty array if none defined

public abstract ConfigurableListableBeanFactory getBeanFactory ()

Subclasses must return their internal bean factory here. They should implement the lookup efficiently, so that it can be called repeatedly without a performance penalty.

Note: Subclasses should check whether the context is still active before returning the internal bean factory. The internal factory should generally be considered unavailable once the context has been closed.

Returns
  • this application context's internal bean factory (never null)
Throws
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 already

public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors ()

Return the list of BeanFactoryPostProcessors that will get applied to the internal BeanFactory.

public String[] getBeanNamesForType (Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)

Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of 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.

Parameters
type the class or interface to match, or null for all bean names
includeNonSingletons 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.
Returns
  • the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none

public String[] getBeanNamesForType (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.

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 getBeanNamesOfType(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.

Parameters
type the class or interface to match, or null for all bean names
Returns
  • the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty array if none

public Map<String, T> getBeansOfType (Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)

Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of 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.

Parameters
type the class or interface to match, or null for all concrete beans
includeNonSingletons 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.
Returns
  • a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

public Map<String, T> getBeansOfType (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.

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.

Parameters
type the class or interface to match, or null for all concrete beans
Returns
  • a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

public Map<StringObject> getBeansWithAnnotation (Class<? extends Annotation> annotationType)

Find all beans whose Class has the supplied Annotation type.

Parameters
annotationType the type of annotation to look for
Returns
  • a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values

public String getDisplayName ()

Return a friendly name for this context.

Returns
  • a display name for this context (never null)

public ConfigurableEnvironment getEnvironment ()

Return the Environment for this application context in configurable form.

public String getId ()

Return the unique id of this application context.

Returns
  • the unique id of the context, or null if none

public String getMessage (MessageSourceResolvable resolvable, Locale locale)

Try to resolve the message using all the attributes contained within the 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.

Parameters
resolvable value object storing attributes required to properly resolve a message
locale the Locale in which to do the lookup
Returns
  • the resolved message

public String getMessage (String code, Object[] args, Locale locale)

Try to resolve the message. Treat as an error if the message can't be found.

Parameters
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 lookup
Returns
  • the resolved message

public String getMessage (String code, Object[] args, String defaultMessage, Locale locale)

Try to resolve the message. Return default message if no message was found.

Parameters
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 fails
locale the Locale in which to do the lookup
Returns
  • the resolved message if the lookup was successful; otherwise the default message passed as a parameter

public ApplicationContext getParent ()

Return the parent context, or null if there is no parent (that is, this context is the root of the context hierarchy).

Returns
  • the parent context, or null if there is no parent

public BeanFactory getParentBeanFactory ()

Return the parent bean factory, or null if there is none.

public Resource[] getResources (String locationPattern)

Resolve the given location pattern into Resource objects.

Overlapping resource entries that point to the same physical resource should be avoided, as far as possible. The result should have set semantics.

Parameters
locationPattern the location pattern to resolve
Returns
  • the corresponding Resource objects
Throws
IOException

public long getStartupDate ()

Return the timestamp (ms) when this context was first loaded.

Returns
  • the timestamp (ms) when this context was first loaded

public Class<?> getType (String name)

Determine the type of the bean with the given name. More specifically, determine the type of object that getBean(Class) would return for the given name.

For a FactoryBean, return the type of object that the FactoryBean creates, as exposed by 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.

Parameters
name the name of the bean to query
Returns
  • the type of the bean, or null if not determinable

public 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.

Returns
  • whether the context is still active

public boolean isPrototype (String name)

Is this bean a prototype? That is, will getBean(Class) 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 isSingleton(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.

Parameters
name the name of the bean to query
Returns
  • whether this bean will always deliver independent instances

public boolean isRunning ()

Check whether this component is currently running.

In the case of a container, this will return true only if all components that apply are currently running.

Returns
  • whether the component is currently running

public boolean isSingleton (String name)

Is this bean a shared singleton? That is, will getBean(Class) 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 isPrototype(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.

Parameters
name the name of the bean to query
Returns
  • whether this bean corresponds to a singleton instance

public boolean isTypeMatch (String name, Class<?> targetType)

Check whether the bean with the given name matches the specified type. More specifically, check whether a getBean(Class) 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.

Parameters
name the name of the bean to query
targetType the type to match against
Returns
  • true if the bean type matches, false if it doesn't match or cannot be determined yet

public void publishEvent (ApplicationEvent event)

Publish the given event to all listeners.

Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannot publish events.

Parameters
event the event to publish (may be application-specific or a standard framework event)

public void refresh ()

Load or refresh the persistent representation of the configuration, which might an XML file, properties file, or relational database schema.

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.

public 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.

Delegates to doClose() for the actual closing procedure.

public void setDisplayName (String displayName)

Set a friendly name for this context. Typically done during initialization of concrete context implementations.

Default is the object id of the context instance.

public void setEnvironment (ConfigurableEnvironment environment)

Set the 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().

Parameters
environment the new environment

public void setId (String id)

Set the unique id of this application context.

Default is the object id of the context instance, or the name of the context bean if the context is itself defined as a bean.

Parameters
id the unique id of the context

public void setParent (ApplicationContext parent)

Set the parent of this application context.

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.

Parameters
parent the parent context

public void start ()

Start this component. Should not throw an exception if the component is already running.

In the case of a container, this will propagate the start signal to all components that apply.

public void stop ()

Stop this component. 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.

public String toString ()

Return information about this context.

Protected Methods

protected void addListener (ApplicationListener<?> listener)

This method is deprecated.
as of Spring 3.0, in favor of addApplicationListener(ApplicationListener)

Subclasses can invoke this method to register a listener. Any beans in the context that are listeners are automatically added.

Note: This method only works within an active application context, i.e. when an ApplicationEventMulticaster is already available. Generally prefer the use of addApplicationListener(ApplicationListener) which is more flexible.

Parameters
listener the listener to register

protected void cancelRefresh (BeansException ex)

Cancel this context's refresh attempt, resetting the active flag after an exception got thrown.

Parameters
ex the exception that led to the cancellation

protected abstract void closeBeanFactory ()

Subclasses must implement this method to release their internal bean factory. This method gets invoked by close() after all other shutdown work.

Should never throw an exception but rather log shutdown failures.

protected ConfigurableEnvironment createEnvironment ()

Create and return a new DefaultEnvironment.

Subclasses may override this method in order to supply a custom ConfigurableEnvironment implementation.

protected void destroyBeans ()

Template method for destroying all beans that this context manages. The default implementation destroy all cached singletons in this context, invoking 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 doClose ()

Actually performs context closing: publishes a ContextClosedEvent and destroys the singletons in the bean factory of this application context.

Called by both close() and a JVM shutdown hook, if any.

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.

protected BeanFactory getInternalParentBeanFactory ()

Return the internal bean factory of the parent context if it implements ConfigurableApplicationContext; else, return the parent context itself.

See Also

protected MessageSource getInternalParentMessageSource ()

Return the internal message source of the parent context if it is an AbstractApplicationContext too; else, return the parent context itself.

protected ResourcePatternResolver getResourcePatternResolver ()

Return the ResourcePatternResolver to use for resolving location patterns into Resource instances. Default is a 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.

Returns
  • the ResourcePatternResolver for this context

protected void initApplicationEventMulticaster ()

Initialize the ApplicationEventMulticaster. Uses SimpleApplicationEventMulticaster if none defined in the context.

protected void initLifecycleProcessor ()

Initialize the LifecycleProcessor. Uses DefaultLifecycleProcessor if none defined in the context.

protected void initMessageSource ()

Initialize the MessageSource. Use parent's if none defined in this context.

protected void initPropertySources ()

Replace any stub property sources with actual instances.

See Also

protected void invokeBeanFactoryPostProcessors (ConfigurableListableBeanFactory beanFactory)

Instantiate and invoke all registered BeanFactoryPostProcessor beans, respecting explicit order if given.

Must be called before singleton instantiation.

protected ConfigurableListableBeanFactory obtainFreshBeanFactory ()

Tell the subclass to refresh the internal bean factory.

Returns
  • the fresh BeanFactory instance

protected void onClose ()

Template method which can be overridden to add context-specific shutdown work. The default implementation is empty.

Called at the end of doClose()'s shutdown procedure, after this context's BeanFactory has been closed. If custom shutdown logic needs to execute while the BeanFactory is still active, override the destroyBeans() method instead.

protected void onRefresh ()

Template method which can be overridden to add context-specific refresh work. Called on initialization of special beans, before instantiation of singletons.

This implementation is empty.

Throws
BeansException in case of errors
See Also

protected void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory)

Modify the application context's internal bean factory after its standard initialization. All bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for registering special BeanPostProcessors etc in certain ApplicationContext implementations.

Parameters
beanFactory the bean factory used by the application context

protected void prepareBeanFactory (ConfigurableListableBeanFactory beanFactory)

Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.

Parameters
beanFactory the BeanFactory to configure

protected void prepareRefresh ()

Prepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources.

protected abstract void refreshBeanFactory ()

Subclasses must implement this method to perform the actual configuration load. The method is invoked by 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.

Throws
BeansException if initialization of the bean factory failed
IllegalStateException if already initialized and multiple refresh attempts are not supported

protected void registerBeanPostProcessors (ConfigurableListableBeanFactory beanFactory)

Instantiate and invoke all registered BeanPostProcessor beans, respecting explicit order if given.

Must be called before any instantiation of application beans.

protected void registerListeners ()

Add beans that implement ApplicationListener as listeners. Doesn't affect other listeners, which can be added without being beans.