org.springframework.beans.factory.support
Class AbstractBeanFactory

java.lang.Object
  extended byorg.springframework.beans.factory.support.AbstractBeanFactory
All Implemented Interfaces:
BeanFactory, ConfigurableBeanFactory, HierarchicalBeanFactory
Direct Known Subclasses:
AbstractAutowireCapableBeanFactory

public abstract class AbstractBeanFactory
extends Object
implements ConfigurableBeanFactory

Abstract superclass for BeanFactory implementations, implementing the ConfigurableBeanFactory SPI interface. Does not assume a listable bean factory: can therefore also be used as base class for bean factory implementations which fetch bean definitions from a variety of backend resources (where bean definition access is an expensive operation).

This class provides singleton/prototype determination, singleton cache, aliases, FactoryBean handling, bean definition merging for child bean definitions, and bean destruction (DisposableBean interface, custom destroy methods). Furthermore, it can manage a bean factory hierarchy, through implementing the HierarchicalBeanFactory interface (superinterface of ConfigurableBeanFactory).

The main template methods to be implemented by subclasses are getBeanDefinition and createBean, retrieving a bean definition for a given bean name or creating a bean instance for a given bean definition. Default implementations for those can be found in DefaultListableBeanFactory or AbstractAutowireCapableBeanFactory, respectively.

Since:
15 April 2001
Author:
Rod Johnson, Juergen Hoeller
See Also:
getBeanDefinition(java.lang.String), createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[]), HierarchicalBeanFactory, DisposableBean, RootBeanDefinition, ChildBeanDefinition, AbstractAutowireCapableBeanFactory.createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[]), DefaultListableBeanFactory.getBeanDefinition(java.lang.String)

Field Summary
protected  Log logger
          Logger available to subclasses
 
Fields inherited from interface org.springframework.beans.factory.BeanFactory
FACTORY_BEAN_PREFIX
 
Constructor Summary
AbstractBeanFactory()
          Create a new AbstractBeanFactory.
AbstractBeanFactory(BeanFactory parentBeanFactory)
          Create a new AbstractBeanFactory with the given parent.
 
Method Summary
 void addBeanPostProcessor(BeanPostProcessor beanPostProcessor)
          Add a new BeanPostProcessor that will get applied to beans created by this factory.
protected  void addSingleton(String beanName, Object singletonObject)
          Add the given singleton object to the singleton cache of this factory.
protected  void checkMergedBeanDefinition(RootBeanDefinition mergedBeanDefinition, String beanName, Class requiredType, Object[] args)
          Check the given merged bean definition, potentially throwing validation exceptions.
 boolean containsBean(String name)
          Does this bean factory contain a bean definition with the given name?
protected abstract  boolean containsBeanDefinition(String beanName)
          Check if this bean factory contains a bean definition with the given name.
 boolean containsSingleton(String beanName)
          Check if this bean factory contains a singleton instance with the given name.
protected abstract  Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)
          Create a bean instance for the given bean definition.
protected  BeanWrapper createBeanWrapper(Object beanInstance)
          Create a new BeanWrapper for the given bean instance.
protected  void destroyBean(String beanName, Object bean)
          Destroy the given bean.
 void destroySingletons()
          Destroy all cached singletons in this factory.
 String[] getAliases(String name)
          Return the aliases for the given bean name, if defined.
 Object getBean(String name)
          Return an instance, which may be shared or independent, of the given bean name.
 Object getBean(String name, Class requiredType)
          Return an instance (possibly shared or independent) of the given bean name.
 Object getBean(String name, Class requiredType, Object[] args)
          Return the bean with the given name, checking the parent bean factory if not found.
 Object getBean(String name, Object[] args)
          Return the bean with the given name, checking the parent bean factory if not found.
protected abstract  BeanDefinition getBeanDefinition(String beanName)
          Return the bean definition for the given bean name.
 List getBeanPostProcessors()
          Return the list of BeanPostProcessors that will get applied to beans created with this factory.
 Map getCustomEditors()
          Return the map of custom editors, with Classes as keys and PropertyEditors as values.
protected  RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
          Return a RootBeanDefinition for the given bean name, by merging with the parent if the given original bean definition is a child bean definition.
protected  RootBeanDefinition getMergedBeanDefinition(String beanName, boolean includingAncestors)
          Return a RootBeanDefinition, even by traversing parent if the parameter is a child definition.
protected  Object getObjectForSharedInstance(String name, Object beanInstance)
          Get the object for the given shared bean, either the bean instance itself or its created object in case of a FactoryBean.
 BeanFactory getParentBeanFactory()
          Return the parent bean factory, or null if there is none.
 int getSingletonCount()
          Return the number of beans in the singleton cache.
 String[] getSingletonNames()
          Return the names of beans in the singleton cache.
 Class getType(String name)
          Determine the type of the bean with the given name.
protected  boolean hasDestructionAwareBeanPostProcessors()
          Return whether this factory holds a DestructionAwareBeanPostProcessor that will get applied to singleton beans on shutdown.
protected  void initBeanWrapper(BeanWrapper bw)
          Initialize the given BeanWrapper with the custom editors registered with this factory.
protected  void invokeCustomDestroyMethod(String beanName, Object bean, String destroyMethodName)
          Invoke the specified custom destroy method on the given bean.
 boolean isFactoryBean(String name)
          Determine whether the bean with the given name is a FactoryBean.
protected  boolean isFactoryDereference(String name)
          Return whether the given name is a factory dereference (beginning with the factory dereference prefix).
 boolean isSingleton(String name)
          Is this bean a singleton?
 void registerAlias(String beanName, String alias)
          Given a bean name, create an alias.
 void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor)
          Register the given custom property editor for all properties of the given type.
protected  void registerDependentBean(String beanName, String dependentBeanName)
          Register a dependent bean for the given bean, to be destroyed before the given bean is destroyed.
protected  void registerDisposableBean(String beanName, DisposableBean bean)
          Add the given bean to the list of further disposable beans in this factory.
protected  void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition)
          Add the given bean to the list of disposable beans in this factory, registering its DisposableBean interface and/or the given destroy method to be called on factory shutdown (if applicable).
 void registerSingleton(String beanName, Object singletonObject)
          Register the given existing object as singleton in the bean factory, under the given bean name.
protected  void removeSingleton(String beanName)
          Remove the bean with the given name from the singleton cache of this factory.
 void setParentBeanFactory(BeanFactory parentBeanFactory)
          Set the parent of this bean factory.
protected  String transformedBeanName(String name)
          Return the bean name, stripping out the factory dereference prefix if necessary, and resolving aliases to canonical names.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

protected final Log logger
Logger available to subclasses

Constructor Detail

AbstractBeanFactory

public AbstractBeanFactory()
Create a new AbstractBeanFactory.


AbstractBeanFactory

public AbstractBeanFactory(BeanFactory parentBeanFactory)
Create a new AbstractBeanFactory with the given parent.

Parameters:
parentBeanFactory - parent bean factory, or null if none
See Also:
getBean(java.lang.String)
Method Detail

getBean

public Object getBean(String name)
               throws BeansException
Description copied from interface: BeanFactory
Return an instance, which may be shared or independent, of the given bean name. This method allows a Spring bean factory 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.

This method delegates to the parent factory if the bean cannot be found in this factory instance.

Specified by:
getBean in interface BeanFactory
Parameters:
name - the name of the bean to return
Returns:
the instance of the bean
Throws:
BeansException - if the bean could not be obtained

getBean

public Object getBean(String name,
                      Class requiredType)
               throws BeansException
Description copied from interface: BeanFactory
Return an instance (possibly shared or independent) of the given bean name.

Behaves the same as getBean(String), but provides a measure of type safety by throwing a Spring BeansException 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).

Specified by:
getBean in interface BeanFactory
Parameters:
name - the name of the bean to return
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 (never null)
Throws:
BeansException - if the bean could not be created

getBean

public Object getBean(String name,
                      Object[] args)
               throws BeansException
Return the bean with the given name, checking the parent bean factory if not found.

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.
Throws:
BeansException

getBean

public Object getBean(String name,
                      Class requiredType,
                      Object[] args)
               throws BeansException
Return the bean with the given name, checking the parent bean factory if not found.

Parameters:
name - the name of the bean to retrieve
requiredType - the required type 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. TODO: We could consider supporting this for constructor args also, but it's really a corner case required for AspectJ integration.
Throws:
BeansException

containsBean

public boolean containsBean(String name)
Description copied from interface: BeanFactory
Does this bean factory contain a bean definition with the given name?

Will ask the parent factory if the bean cannot be found in this factory instance.

Specified by:
containsBean in interface BeanFactory
Parameters:
name - the name of the bean to query
Returns:
whether a bean with the given name is defined

isSingleton

public boolean isSingleton(String name)
                    throws NoSuchBeanDefinitionException
Description copied from interface: BeanFactory
Is this bean a singleton? That is, will getBean() always return the same object?

Will ask the parent factory if the bean cannot be found in this factory instance.

Specified by:
isSingleton in interface BeanFactory
Parameters:
name - the name of the bean to query
Returns:
is this bean a singleton
Throws:
NoSuchBeanDefinitionException - if there is no bean with the given name

getType

public Class getType(String name)
              throws NoSuchBeanDefinitionException
Description copied from interface: BeanFactory
Determine the type of the bean with the given name. More specifically, checks the type of object that getBean would return. For a FactoryBean, returns the type of object that the FactoryBean creates.

Specified by:
getType in interface BeanFactory
Parameters:
name - the name of the bean to query
Returns:
the type of the bean, or null if not determinable
Throws:
NoSuchBeanDefinitionException - if there is no bean with the given name
See Also:
BeanFactory.getBean(java.lang.String), FactoryBean.getObjectType()

getAliases

public String[] getAliases(String name)
                    throws NoSuchBeanDefinitionException
Description copied from interface: BeanFactory
Return the aliases for the given bean name, if defined.

Will ask the parent factory if the bean cannot be found in this factory instance.

Specified by:
getAliases in interface BeanFactory
Parameters:
name - the bean name to check for aliases
Returns:
the aliases, or an empty array if none
Throws:
NoSuchBeanDefinitionException - if there's no such bean definition

getParentBeanFactory

public BeanFactory getParentBeanFactory()
Description copied from interface: HierarchicalBeanFactory
Return the parent bean factory, or null if there is none.

Specified by:
getParentBeanFactory in interface HierarchicalBeanFactory

setParentBeanFactory

public void setParentBeanFactory(BeanFactory parentBeanFactory)
Description copied from interface: ConfigurableBeanFactory
Set the parent of this bean factory.

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.

Specified by:
setParentBeanFactory in interface ConfigurableBeanFactory
Parameters:
parentBeanFactory - the parent bean factory

registerCustomEditor

public void registerCustomEditor(Class requiredType,
                                 PropertyEditor propertyEditor)
Description copied from interface: ConfigurableBeanFactory
Register the given custom property editor for all properties of the given type. To be invoked during factory configuration.

Specified by:
registerCustomEditor in interface ConfigurableBeanFactory
Parameters:
requiredType - type of the property
propertyEditor - editor to register

getCustomEditors

public Map getCustomEditors()
Return the map of custom editors, with Classes as keys and PropertyEditors as values.


addBeanPostProcessor

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor)
Description copied from interface: ConfigurableBeanFactory
Add a new BeanPostProcessor that will get applied to beans created by this factory. To be invoked during factory configuration.

Specified by:
addBeanPostProcessor in interface ConfigurableBeanFactory
Parameters:
beanPostProcessor - the bean processor to register

getBeanPostProcessors

public List getBeanPostProcessors()
Return the list of BeanPostProcessors that will get applied to beans created with this factory.


hasDestructionAwareBeanPostProcessors

protected boolean hasDestructionAwareBeanPostProcessors()
Return whether this factory holds a DestructionAwareBeanPostProcessor that will get applied to singleton beans on shutdown.

See Also:
addBeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor), DestructionAwareBeanPostProcessor

createBeanWrapper

protected BeanWrapper createBeanWrapper(Object beanInstance)
Create a new BeanWrapper for the given bean instance.

Default implementation creates a BeanWrapperImpl. Can be overridden for custom BeanWrapper adaptations.

Parameters:
beanInstance - the bean instance to create the BeanWrapper for, or null for a BeanWrapper that does not yet contain a target object
Returns:
the BeanWrapper

initBeanWrapper

protected void initBeanWrapper(BeanWrapper bw)
Initialize the given BeanWrapper with the custom editors registered with this factory. To be called for BeanWrappers that will create and populate bean instances.

Parameters:
bw - the BeanWrapper to initialize

registerAlias

public void registerAlias(String beanName,
                          String alias)
                   throws BeanDefinitionStoreException
Description copied from interface: ConfigurableBeanFactory
Given a bean name, create an alias. We typically use this method to support names that are illegal within XML ids (used for bean names).

Typically invoked during factory configuration, but can also be used for runtime registration of aliases. Therefore, a factory implementation should synchronize alias access.

Specified by:
registerAlias in interface ConfigurableBeanFactory
Parameters:
beanName - name of the bean
alias - alias that will behave the same as the bean name
Throws:
BeanDefinitionStoreException

registerSingleton

public void registerSingleton(String beanName,
                              Object singletonObject)
                       throws BeanDefinitionStoreException
Description copied from interface: ConfigurableBeanFactory
Register the given existing object as singleton in the bean factory, under the given bean name.

The given instance is supposed to be fully initialized; the factory will not perform any initialization callbacks (in particular, it won't call InitializingBean's afterPropertiesSet method). The given instance will not receive any destruction callbacks (like DisposableBean's destroy method) either.

Register a bean definition instead of an existing instance if your bean is supposed to receive initialization and/or destruction callbacks.

Typically invoked during factory configuration, but can also be used for runtime registration of singletons. Therefore, a factory implementation should synchronize singleton access; it will have to do this anyway if it supports lazy initialization of singletons.

Specified by:
registerSingleton in interface ConfigurableBeanFactory
Parameters:
beanName - name of the bean
singletonObject - the existing object
Throws:
BeanDefinitionStoreException
See Also:
InitializingBean.afterPropertiesSet(), DisposableBean.destroy(), DefaultListableBeanFactory.registerBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition)

addSingleton

protected void addSingleton(String beanName,
                            Object singletonObject)
Add the given singleton object to the singleton cache of this factory.

To be called for eager registration of singletons, e.g. to be able to resolve circular references.

Parameters:
beanName - the name of the bean
singletonObject - the singleton object

removeSingleton

protected void removeSingleton(String beanName)
Remove the bean with the given name from the singleton cache of this factory.

To be able to clean up eager registration of a singleton if creation failed.

Parameters:
beanName - the name of the bean

getSingletonCount

public int getSingletonCount()
Return the number of beans in the singleton cache.

Does not consider any hierarchy this factory may participate in.


getSingletonNames

public String[] getSingletonNames()
Return the names of beans in the singleton cache.

Does not consider any hierarchy this factory may participate in.


containsSingleton

public boolean containsSingleton(String beanName)
Description copied from interface: ConfigurableBeanFactory
Check if this bean factory contains a singleton instance with the given name. Only checks already instantiated singletons; does not return true for singleton bean definitions that have not been instantiated yet.

The main purpose of this method is to check manually registered singletons (see registerSingleton). Can also be used to check whether a singleton defined by a bean definition has already been created.

To check whether a bean factory contains a bean definition with a given name, use ListableBeanFactory's containsBeanDefinition. Calling both containsBeanDefinition and containsSingleton answers whether a specific bean factory contains an own bean with the given name.

Use BeanFactory's containsBean for general checks whether the factory knows about a bean with a given name (whether manually registed singleton instance or created by bean definition), also checking ancestor factories.

Specified by:
containsSingleton in interface ConfigurableBeanFactory
Parameters:
beanName - the name of the bean to look for
Returns:
if this bean factory contains a singleton instance with the given name
See Also:
ConfigurableBeanFactory.registerSingleton(java.lang.String, java.lang.Object), BeanFactory.containsBean(java.lang.String), ListableBeanFactory.containsBeanDefinition(java.lang.String)

destroySingletons

public void destroySingletons()
Description copied from interface: ConfigurableBeanFactory
Destroy all cached singletons in this factory. To be called on shutdown of a factory.

Specified by:
destroySingletons in interface ConfigurableBeanFactory

isFactoryDereference

protected boolean isFactoryDereference(String name)
Return whether the given name is a factory dereference (beginning with the factory dereference prefix).

See Also:
BeanFactory.FACTORY_BEAN_PREFIX, BeanFactoryUtils.isFactoryDereference(java.lang.String)

transformedBeanName

protected String transformedBeanName(String name)
Return the bean name, stripping out the factory dereference prefix if necessary, and resolving aliases to canonical names.


getMergedBeanDefinition

protected RootBeanDefinition getMergedBeanDefinition(String beanName,
                                                     boolean includingAncestors)
                                              throws BeansException
Return a RootBeanDefinition, even by traversing parent if the parameter is a child definition. Can ask the parent bean factory if not found in this instance.

Parameters:
beanName - the name of the bean definition
includingAncestors - whether to ask the parent bean factory if not found in this instance
Returns:
a merged RootBeanDefinition with overridden properties
Throws:
BeansException

getMergedBeanDefinition

protected RootBeanDefinition getMergedBeanDefinition(String beanName,
                                                     BeanDefinition bd)
                                              throws BeansException
Return a RootBeanDefinition for the given bean name, by merging with the parent if the given original bean definition is a child bean definition.

Parameters:
beanName - the name of the bean definition
bd - the original bean definition (Root/ChildBeanDefinition)
Returns:
a merged RootBeanDefinition with overridden properties
Throws:
BeansException

checkMergedBeanDefinition

protected void checkMergedBeanDefinition(RootBeanDefinition mergedBeanDefinition,
                                         String beanName,
                                         Class requiredType,
                                         Object[] args)
                                  throws BeansException
Check the given merged bean definition, potentially throwing validation exceptions.

Parameters:
mergedBeanDefinition - the bean definition to check
beanName - the name of the bean
requiredType - the required type of the bean
args - the arguments for bean creation, if any
Throws:
BeansException - in case of validation failure

getObjectForSharedInstance

protected Object getObjectForSharedInstance(String name,
                                            Object beanInstance)
                                     throws BeansException
Get the object for the given shared bean, either the bean instance itself or its created object in case of a FactoryBean.

Parameters:
name - name that may include factory dereference prefix
beanInstance - the shared bean instance
Returns:
the singleton instance of the bean
Throws:
BeansException

isFactoryBean

public boolean isFactoryBean(String name)
                      throws NoSuchBeanDefinitionException
Determine whether the bean with the given name is a FactoryBean.

Parameters:
name - the name of the bean to check
Throws:
NoSuchBeanDefinitionException - if there is no bean with the given name

registerDisposableBeanIfNecessary

protected void registerDisposableBeanIfNecessary(String beanName,
                                                 Object bean,
                                                 RootBeanDefinition mergedBeanDefinition)
Add the given bean to the list of disposable beans in this factory, registering its DisposableBean interface and/or the given destroy method to be called on factory shutdown (if applicable). Only applies to singletons.

Also registers bean as dependent on other beans, according to the "depends-on" configuration in the bean definition.

Parameters:
beanName - the name of the bean
bean - the bean instance
mergedBeanDefinition - the bean definition for the bean
See Also:
AbstractBeanDefinition.isSingleton(), AbstractBeanDefinition.getDependsOn(), registerDisposableBean(java.lang.String, org.springframework.beans.factory.DisposableBean), registerDependentBean(java.lang.String, java.lang.String)

registerDisposableBean

protected void registerDisposableBean(String beanName,
                                      DisposableBean bean)
Add the given bean to the list of further disposable beans in this factory.

Parameters:
beanName - the name of the bean
bean - the bean instance

registerDependentBean

protected void registerDependentBean(String beanName,
                                     String dependentBeanName)
Register a dependent bean for the given bean, to be destroyed before the given bean is destroyed.

Parameters:
beanName - the name of the bean
dependentBeanName - the name of the dependent bean

destroyBean

protected void destroyBean(String beanName,
                           Object bean)
Destroy the given bean. Must destroy beans that depend on the given bean before the bean itself. Should not throw any exceptions.

Parameters:
beanName - name of the bean
bean - the bean instance to destroy

invokeCustomDestroyMethod

protected void invokeCustomDestroyMethod(String beanName,
                                         Object bean,
                                         String destroyMethodName)
Invoke the specified custom destroy method on the given bean.

This implementation invokes a no-arg method if found, else checking for a method with a single boolean argument (passing in "true", assuming a "force" parameter), else logging an error.

Can be overridden in subclasses for custom resolution of destroy methods with arguments.

Parameters:
beanName - the bean has in the factory. Used for debug output.
bean - new bean instance we may need to notify of destruction
destroyMethodName - the name of the custom destroy method

containsBeanDefinition

protected abstract 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. Invoked by containsBean when no cached singleton instance is found.

Depending on the nature of the concrete bean factory implementation, this operation might be expensive (for example, because of directory lookups in external registries). However, for listable bean factories, this usually just amounts to a local hash lookup: The operation is therefore part of the public interface there. The same implementation can serve for both this template method and the public interface method in that case.

Parameters:
beanName - the name of the bean to look for
Returns:
if this bean factory contains a bean definition with the given name
See Also:
containsBean(java.lang.String), ListableBeanFactory.containsBeanDefinition(java.lang.String)

getBeanDefinition

protected abstract BeanDefinition getBeanDefinition(String beanName)
                                             throws BeansException
Return the bean definition for the given bean name. Subclasses should normally implement caching, as this method is invoked by this class every time bean definition metadata is needed.

Depending on the nature of the concrete bean factory implementation, this operation might be expensive (for example, because of directory lookups in external registries). However, for listable bean factories, this usually just amounts to a local hash lookup: The operation is therefore part of the public interface there. The same implementation can serve for both this template method and the public interface method in that case.

Parameters:
beanName - name of the bean to find a definition for
Returns:
the BeanDefinition for this prototype name. Must never return null.
Throws:
NoSuchBeanDefinitionException - if the bean definition cannot be resolved
BeansException - in case of errors
See Also:
RootBeanDefinition, ChildBeanDefinition, ConfigurableListableBeanFactory.getBeanDefinition(java.lang.String)

createBean

protected abstract Object createBean(String beanName,
                                     RootBeanDefinition mergedBeanDefinition,
                                     Object[] args)
                              throws BeansException
Create a bean instance for the given bean definition. The bean definition will already have been merged with the parent definition in case of a child definition.

All the other methods in this class invoke this method, although beans may be cached after being instantiated by this method. All bean instantiation within this class is performed by this method.

Parameters:
beanName - name of the bean
mergedBeanDefinition - the bean definition for the bean
args - arguments to use if creating a prototype using explicit arguments to a static factory method. This parameter must be null except in this case.
Returns:
a new instance of the bean
Throws:
BeansException - in case of errors


Copyright (C) 2003-2004 The Spring Framework Project.