Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright 2002-2008 the original author or authors.
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package org.springframework.beans.factory.support;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  import java.util.TreeSet;
  
Abstract bean factory superclass that implements default bean creation, with the full capabilities specified by the RootBeanDefinition class. Implements the org.springframework.beans.factory.config.AutowireCapableBeanFactory interface in addition to AbstractBeanFactory's createBean(java.lang.Class) method.

Provides bean creation (with constructor resolution), property population, wiring (including autowiring), and initialization. Handles runtime bean references, resolves managed collections, calls initialization methods, etc. Supports autowiring constructors, properties by name, and properties by type.

The main template method to be implemented by subclasses is org.springframework.beans.factory.config.AutowireCapableBeanFactory.resolveDependency(org.springframework.beans.factory.config.DependencyDescriptor,java.lang.String,java.util.Set,org.springframework.beans.TypeConverter), used for autowiring by type. In case of a factory which is capable of searching its bean definitions, matching beans will typically be implemented through such a search. For other factory styles, simplified matching algorithms can be implemented.

Note that this class does not assume or implement bean definition registry capabilities. See DefaultListableBeanFactory for an implementation of the org.springframework.beans.factory.ListableBeanFactory and BeanDefinitionRegistry interfaces, which represent the API and SPI view of such a factory, respectively.

Author(s):
Rod Johnson
Juergen Hoeller
Rob Harrop
Mark Fisher
Since:
13.02.2004
See also:
RootBeanDefinition
DefaultListableBeanFactory
BeanDefinitionRegistry
 
 public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
 
Whether to automatically try to resolve circular references between beans
 
 	private boolean allowCircularReferences = true;

Whether to resort to injecting a raw bean instance in case of circular reference, even if the injected bean eventually got wrapped.
 
 	private boolean allowRawInjectionDespiteWrapping = false;

Dependency types to ignore on dependency check and autowire, as Set of Class objects: for example, String. Default is none.
 
 	private final Set ignoredDependencyTypes = new HashSet();

Dependency interfaces to ignore on dependency check and autowire, as Set of Class objects. By default, only the BeanFactory interface is ignored.
 
 	private final Set ignoredDependencyInterfaces = new HashSet();

Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper
 
 	private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16);

Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array
 
 	private final Map filteredPropertyDescriptorsCache = new HashMap();


Create a new AbstractAutowireCapableBeanFactory.
 
 		super();
 	}

Create a new AbstractAutowireCapableBeanFactory with the given parent.

Parameters:
parentBeanFactory parent bean factory, or null if none
 
 	public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
 		this();
 		setParentBeanFactory(parentBeanFactory);
 	}


Set the instantiation strategy to use for creating bean instances. Default is CglibSubclassingInstantiationStrategy.

 
 	public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
 		this. = instantiationStrategy;
 	}

Return the instantiation strategy to use for creating bean instances.
 
 		return this.;
 	}

Set whether to allow circular references between beans - and automatically try to resolve them.

Note that circular reference resolution means that one of the involved beans will receive a reference to another bean that is not fully initialized yet. This can lead to subtle and not-so-subtle side effects on initialization; it does work fine for many scenarios, though.

Default is "true". Turn this off to throw an exception when encountering a circular reference, disallowing them completely.

NOTE: It is generally recommended to not rely on circular references between your beans. Refactor your application logic to have the two beans involved delegate to a third bean that encapsulates their common logic.

 
 	public void setAllowCircularReferences(boolean allowCircularReferences) {
 		this. = allowCircularReferences;
 	}

Set whether to allow the raw injection of a bean instance into some other bean's property, despite the injected bean eventually getting wrapped (for example, through AOP auto-proxying).

This will only be used as a last resort in case of a circular reference that cannot be resolved otherwise: essentially, preferring a raw instance getting injected over a failure of the entire bean wiring process.

Default is "false", as of Spring 2.0. Turn this on to allow for non-wrapped raw beans injected into some of your references, which was Spring 1.2's (arguably unclean) default behavior.

NOTE: It is generally recommended to not rely on circular references between your beans, in particular with auto-proxying involved.

 
 	public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
 		this. = allowRawInjectionDespiteWrapping;
 	}

Ignore the given dependency type for autowiring: for example, String. Default is none.
 
 	public void ignoreDependencyType(Class type) {
 	}

Ignore the given dependency interface for autowiring.

This will typically be used by application contexts to register dependencies that are resolved in other ways, like BeanFactory through BeanFactoryAware or ApplicationContext through ApplicationContextAware.

By default, only the BeanFactoryAware interface is ignored. For further types to ignore, invoke this method for each type.

See also:
org.springframework.beans.factory.BeanFactoryAware
org.springframework.context.ApplicationContextAware
 
 	public void ignoreDependencyInterface(Class ifc) {
 	}
 
 
 	public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
 		super.copyConfigurationFrom(otherFactory);
 		if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
 			AbstractAutowireCapableBeanFactory otherAutowireFactory =
 			this. = otherAutowireFactory.instantiationStrategy;
 			this. = otherAutowireFactory.allowCircularReferences;
 			this..addAll(otherAutowireFactory.ignoredDependencyTypes);
 			this..addAll(otherAutowireFactory.ignoredDependencyInterfaces);
 		}
 	}
 
 
 	//-------------------------------------------------------------------------
 	// Typical methods for creating and populating external bean instances
 	//-------------------------------------------------------------------------
 
 	public Object createBean(Class beanClassthrows BeansException {
 		// Use prototype bean definition, to avoid registering bean as dependent bean.
 		RootBeanDefinition bd = new RootBeanDefinition(beanClass);
 		return createBean(beanClass.getName(), bdnull);
 	}
 
 	public void autowireBean(Object existingBean) {
 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
 		RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
 		populateBean(bd.getBeanClass().getName(), bdbw);
 	}
 
 	public Object configureBean(Object existingBeanString beanNamethrows BeansException {
 		markBeanAsCreated(beanName);
 		RootBeanDefinition bd = null;
 		if (mbd instanceof RootBeanDefinition) {
 				bd = rbd;
 			}
 		}
 		if (bd == null) {
 			bd = new RootBeanDefinition(mbd);
 		}
 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
 		populateBean(beanNamebdbw);
 		return initializeBean(beanNameexistingBeanbd);
 	}
 
 	public Object resolveDependency(DependencyDescriptor descriptorString beanNamethrows BeansException {
 		return resolveDependency(descriptorbeanNamenullnull);
 	}
 
 
 	//-------------------------------------------------------------------------
 	// Specialized methods for fine-grained control over the bean lifecycle
 	//-------------------------------------------------------------------------
 
 	public Object createBean(Class beanClassint autowireModeboolean dependencyCheckthrows BeansException {
 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
 		RootBeanDefinition bd = new RootBeanDefinition(beanClassautowireModedependencyCheck);
 		return createBean(beanClass.getName(), bdnull);
 	}
 
 	public Object autowire(Class beanClassint autowireModeboolean dependencyCheckthrows BeansException {
 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
 		RootBeanDefinition bd = new RootBeanDefinition(beanClassautowireModedependencyCheck);
 			return autowireConstructor(beanClass.getName(), bdnullnull).getWrappedInstance();
 		}
 		else {
 			Object bean = getInstantiationStrategy().instantiate(bdnullthis);
 			populateBean(beanClass.getName(), bdnew BeanWrapperImpl(bean));
 			return bean;
 		}
 	}
 
 	public void autowireBeanProperties(Object existingBeanint autowireModeboolean dependencyCheck)
 			throws BeansException {
 
 		if (autowireMode == ) {
 			throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance");
 		}
 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
 				new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireModedependencyCheck);
 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
 		populateBean(bd.getBeanClass().getName(), bdbw);
 	}
 
 	public void applyBeanPropertyValues(Object existingBeanString beanNamethrows BeansException {
 		markBeanAsCreated(beanName);
 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
 		applyPropertyValues(beanNamebdbwbd.getPropertyValues());
 	}
 
 	public Object initializeBean(Object existingBeanString beanName) {
 		return initializeBean(beanNameexistingBeannull);
 	}
 
 			throws BeansException {
 
 		Object result = existingBean;
 		for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 			BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 			result = beanProcessor.postProcessBeforeInitialization(resultbeanName);
 		}
 		return result;
 	}
 
 	public Object applyBeanPostProcessorsAfterInitialization(Object existingBeanString beanName)
 			throws BeansException {
 
 		Object result = existingBean;
 		for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 			BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 			result = beanProcessor.postProcessAfterInitialization(resultbeanName);
 		}
 		return result;
 	}
 
 
 	//---------------------------------------------------------------------
 	// Implementation of relevant AbstractBeanFactory template methods
 	//---------------------------------------------------------------------
 
Central method of this class: creates a bean instance, populates the bean instance, applies post-processors, etc.

 
 	protected Object createBean(final String beanNamefinal RootBeanDefinition mbdfinal Object[] args)
 
 		AccessControlContext acc = AccessController.getContext();
 		return AccessController.doPrivileged(new PrivilegedAction() {
 			public Object run() {
 					.debug("Creating instance of bean '" + beanName + "'");
 				}
 				// Make sure bean class is actually resolved at this point.
 				resolveBeanClass(mbdbeanName);
 
 				// Prepare method overrides.
 				try {
 				}
 							beanName"Validation of method overrides failed"ex);
 				}
 
 				try {
 					// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
 					Object bean = resolveBeforeInstantiation(beanNamembd);
 					if (bean != null) {
 						return bean;
 					}
 				}
 				catch (Throwable ex) {
 					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 							"BeanPostProcessor before instantiation of bean failed"ex);
 				}
 
 				Object beanInstance = doCreateBean(beanNamembdargs);
 					.debug("Finished creating instance of bean '" + beanName + "'");
 				}
 				return beanInstance;
 			}
 		}, acc);
 	}

Actually create the specified bean. Pre-creation processing has already happened at this point, e.g. checking postProcessBeforeInstantiation callbacks.

Differentiates between default bean instantiation, use of a factory method, and autowiring a constructor.

Parameters:
beanName the name of the bean
mbd the merged 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:
org.springframework.beans.factory.BeanCreationException if the bean could not be created
See also:
instantiateBean(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition)
instantiateUsingFactoryMethod(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition,java.lang.Object[])
autowireConstructor(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition,java.lang.reflect.Constructor[],java.lang.Object[])
 
 	protected Object doCreateBean(final String beanNamefinal RootBeanDefinition mbdfinal Object[] args) {
 		// Instantiate the bean.
 		BeanWrapper instanceWrapper = null;
 		if (mbd.isSingleton()) {
 			instanceWrapper = (BeanWrapperthis..remove(beanName);
 		}
 		if (instanceWrapper == null) {
 			instanceWrapper = createBeanInstance(beanNamembdargs);
 		}
 		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
 		Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
 
 		// Allow post-processors to modify the merged bean definition.
 		synchronized (mbd.postProcessingLock) {
 			if (!mbd.postProcessed) {
 				applyMergedBeanDefinitionPostProcessors(mbdbeanTypebeanName);
 				mbd.postProcessed = true;
 			}
 		}
 
 		// Eagerly cache singletons to be able to resolve circular references
 		// even when triggered by lifecycle interfaces like BeanFactoryAware.
 		boolean earlySingletonExposure = (mbd.isSingleton() && this. &&
 		if (earlySingletonExposure) {
 				.debug("Eagerly caching bean '" + beanName +
 						"' to allow for resolving potential circular references");
 			}
 			addSingletonFactory(beanNamenew ObjectFactory() {
 				public Object getObject() throws BeansException {
 					return getEarlyBeanReference(beanNamembdbean);
 				}
 			});
 		}
 
 		// Initialize the bean instance.
 		Object exposedObject = bean;
 		try {
 			populateBean(beanNamembdinstanceWrapper);
 			exposedObject = initializeBean(beanNameexposedObjectmbd);
 		}
 		catch (Throwable ex) {
 			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationExceptionex).getBeanName())) {
 				throw (BeanCreationExceptionex;
 			}
 			else {
 				throw new BeanCreationException(mbd.getResourceDescription(), beanName"Initialization of bean failed"ex);
 			}
 		}
 
 		if (earlySingletonExposure) {
 			Object earlySingletonReference = getSingleton(beanNamefalse);
 			if (earlySingletonReference != null) {
 				if (exposedObject == bean) {
 					exposedObject = earlySingletonReference;
 				}
 				else if (!this. && hasDependentBean(beanName)) {
 					String[] dependentBeans = getDependentBeans(beanName);
 					Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
 					for (int i = 0; i < dependentBeans.lengthi++) {
 						String dependentBean = dependentBeans[i];
 							actualDependentBeans.add(dependentBean);
 						}
 					}
 					if (!actualDependentBeans.isEmpty()) {
 						throw new BeanCurrentlyInCreationException(beanName,
 								"Bean with name '" + beanName + "' has been injected into other beans [" +
 								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
 								"] in its raw version as part of a circular reference, but has eventually been " +
 								"wrapped. This means that said other beans do not use the final version of the " +
 								"bean. This is often the result of over-eager type matching - consider using " +
 								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
 					}
 				}
 			}
 		}
 
 		// Register bean as disposable.
 		registerDisposableBeanIfNecessary(beanNamebeanmbd);
 
 		return exposedObject;
 	}
 
 	protected Class predictBeanType(String beanNameRootBeanDefinition mbdClass[] typesToMatch) {
 		Class beanClass = null;
 		if (mbd.getFactoryMethodName() != null) {
 			beanClass = getTypeForFactoryMethod(beanNamembdtypesToMatch);
 		}
 		else {
 			beanClass = resolveBeanClass(mbdbeanNametypesToMatch);
 		}
 		// Apply SmartInstantiationAwareBeanPostProcessors to predict the
 		// eventual type after a before-instantiation shortcut.
 		if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
 			for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
 					Class processedType = ibp.predictBeanType(beanClassbeanName);
 					if (processedType != null) {
 						return processedType;
 					}
 				}
 			}
 		}
 		return beanClass;
 	}

Determine the bean type for the given bean definition which is based on a factory method. Only called if there is no singleton instance registered for the target bean already.

This implementation determines the type matching createBean(java.lang.Class)'s different creation strategies. As far as possible, we'll perform static type checking to avoid creation of the target bean.

Parameters:
beanName the name of the bean (for error handling purposes)
mbd the merged bean definition for the bean
typesToMatch the types to match in case of internal type matching purposes (also signals that the returned Class will never be exposed to application code)
Returns:
the type for the bean if determinable, or null else
See also:
createBean(java.lang.Class)
 
 	protected Class getTypeForFactoryMethod(String beanNameRootBeanDefinition mbdClass[] typesToMatch) {
 		Class factoryClass = null;
 		boolean isStatic = true;
 
 		String factoryBeanName = mbd.getFactoryBeanName();
 		if (factoryBeanName != null) {
 			if (factoryBeanName.equals(beanName)) {
 						"factory-bean reference points back to the same bean definition");
 			}
 			// Check declared factory method return type on factory class.
 			factoryClass = getType(factoryBeanName);
 			isStatic = false;
 		}
 		else {
 			// Check declared factory method return type on bean class.
 			factoryClass = resolveBeanClass(mbdbeanNametypesToMatch);
 		}
 
 		if (factoryClass == null) {
 			return null;
 		}
 
 		// If all factory methods have the same return type, return that type.
 		// Can't clearly figure out exact method due to type converting / autowiring!
 		int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount();
 		Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass);
 		Set returnTypes = new HashSet(1);
 		for (int i = 0; i < candidates.lengthi++) {
 			Method factoryMethod = candidates[i];
 			if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
 					factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
 					factoryMethod.getParameterTypes().length >= minNrOfArgs) {
 				returnTypes.add(factoryMethod.getReturnType());
 			}
 		}
 
 		if (returnTypes.size() == 1) {
 			// Clear return type found: all factory methods return same type.
 			return (ClassreturnTypes.iterator().next();
 		}
 		else {
 			// Ambiguous return types found: return null to indicate "not determinable".
 			return null;
 		}
 	}

This implementation checks the FactoryBean's getObjectType method on a plain instance of the FactoryBean, without bean properties applied yet. If this doesn't return a type yet, a full creation of the FactoryBean is used as fallback (through delegation to the superclass's implementation).

The shortcut check for a FactoryBean is only applied in case of a singleton FactoryBean. If the FactoryBean instance itself is not kept as singleton, it will be fully created to check the type of its exposed object.

 
 	protected Class getTypeForFactoryBean(String beanNameRootBeanDefinition mbd) {
 		FactoryBean fb = (mbd.isSingleton() ?
 
 		if (fb != null) {
 			// Try to obtain the FactoryBean's object type from this early stage of the instance.
 			Class objectType = getTypeForFactoryBean(fb);
 			if (objectType != null) {
 				return objectType;
 			}
 		}
 
 		// No type found - fall back to full creation of the FactoryBean instance.
 		return super.getTypeForFactoryBean(beanNamembd);
 	}

Obtain a reference for early access to the specified bean, typically for the purpose of resolving a circular reference.

Parameters:
beanName the name of the bean (for error handling purposes)
mbd the merged bean definition for the bean
bean the raw bean instance
Returns:
the object to expose as bean reference
 
 	protected Object getEarlyBeanReference(String beanNameRootBeanDefinition mbdObject bean) {
 		Object exposedObject = bean;
 			for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
 					exposedObject = ibp.getEarlyBeanReference(exposedObjectbeanName);
 				}
 			}
 		}
 		return exposedObject;
 	}
 
 
 	//---------------------------------------------------------------------
 	// Implementation methods
 	//---------------------------------------------------------------------
 
Obtain a "shortcut" singleton FactoryBean instance to use for a getObjectType() call, without full initialization of the FactoryBean.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
Returns:
the FactoryBean instance, or null to indicate that we couldn't obtain a shortcut FactoryBean instance
 
 		synchronized (getSingletonMutex()) {
 			if (bw != null) {
 			}
 			if (isSingletonCurrentlyInCreation(beanName)) {
 				return null;
 			}
 			Object instance = null;
 			try {
 				// Mark this bean as currently in creation, even if just partially.
 				// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
 				instance = resolveBeforeInstantiation(beanNamembd);
 				if (instance == null) {
 					bw = createBeanInstance(beanNamembdnull);
 					instance = bw.getWrappedInstance();
 				}
 			}
 			finally {
 				// Finished partial creation of this bean.
 			}
 			FactoryBean fb = getFactoryBean(beanNameinstance);
 			if (bw != null) {
 				this..put(beanNamebw);
 			}
 			return fb;
 		}
 	}

Obtain a "shortcut" non-singleton FactoryBean instance to use for a getObjectType() call, without full initialization of the FactoryBean.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
Returns:
the FactoryBean instance, or null to indicate that we couldn't obtain a shortcut FactoryBean instance
 
 		if (isPrototypeCurrentlyInCreation(beanName)) {
 			return null;
 		}
 		Object instance = null;
 		try {
 			// Mark this bean as currently in creation, even if just partially.
 			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
 			instance = resolveBeforeInstantiation(beanNamembd);
 			if (instance == null) {
 				BeanWrapper bw = createBeanInstance(beanNamembdnull);
 				instance = bw.getWrappedInstance();
 			}
 		}
 		finally {
 			// Finished partial creation of this bean.
 		}
 		return getFactoryBean(beanNameinstance);
 	}

Apply MergedBeanDefinitionPostProcessors to the specified bean definition, invoking their postProcessMergedBeanDefinition methods.

Parameters:
mbd the merged bean definition for the bean
beanType the actual type of the managed bean instance
beanName the name of the bean
Throws:
org.springframework.beans.BeansException if any post-processing failed
See also:
MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition,java.lang.Class,java.lang.String)
 
 	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbdClass beanTypeString beanName)
 			throws BeansException {
 
 		for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 			BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 			if (beanProcessor instanceof MergedBeanDefinitionPostProcessor) {
 				bdp.postProcessMergedBeanDefinition(mbdbeanTypebeanName);
 			}
 		}
 	}

Apply before-instantiation post-processors, resolving whether there is a before-instantiation shortcut for the specified bean.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
Returns:
the shortcut-determined bean instance, or null if none
 
 		Object bean = null;
 		if (!..equals(mbd.beforeInstantiationResolved)) {
 			// Make sure bean class is actually resolved at this point.
 				if (bean != null) {
 					bean = applyBeanPostProcessorsAfterInitialization(beanbeanName);
 				}
 			}
 			mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null);
 		}
 		return bean;
 	}

Apply InstantiationAwareBeanPostProcessors to the specified bean definition (by class and name), invoking their postProcessBeforeInstantiation methods.

Any returned object will be used as the bean instead of actually instantiating the target bean. A null return value from the post-processor will result in the target bean being instantiated.

Parameters:
beanClass the class of the bean to be instantiated
beanName the name of the bean
Returns:
the bean object to use instead of a default instance of the target bean, or null
Throws:
org.springframework.beans.BeansException if any post-processing failed
See also:
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(java.lang.Class,java.lang.String)
 
 	protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClassString beanName)
 			throws BeansException {
 
 		for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 			BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 			if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
 				Object result = ibp.postProcessBeforeInstantiation(beanClassbeanName);
 				if (result != null) {
 					return result;
 				}
 			}
 		}
 		return null;
 	}

Create a new instance for the specified bean, using an appropriate instantiation strategy: factory method, constructor autowiring, or simple instantiation.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
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:
BeanWrapper for the new instance
See also:
instantiateUsingFactoryMethod(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition,java.lang.Object[])
autowireConstructor(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition,java.lang.reflect.Constructor[],java.lang.Object[])
instantiateBean(java.lang.String,org.springframework.beans.factory.support.RootBeanDefinition)
 
 	protected BeanWrapper createBeanInstance(String beanNameRootBeanDefinition mbdObject[] args) {
 		// Make sure bean class is actually resolved at this point.
 		Class beanClass = resolveBeanClass(mbdbeanName);
 
 		if (mbd.getFactoryMethodName() != null)  {
 			return instantiateUsingFactoryMethod(beanNamembdargs);
 		}
 
 		// Shortcut when re-creating the same bean...
 		if (mbd.resolvedConstructorOrFactoryMethod != null) {
 			if (mbd.constructorArgumentsResolved) {
 				return autowireConstructor(beanNamembdnullargs);
 			}
 			else {
 				return instantiateBean(beanNamembd);
 			}
 		}
 
 		// Need to determine the constructor...
 		Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClassbeanName);
 		if (ctors != null ||
 				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
 			return autowireConstructor(beanNamembdctorsargs);
 		}
 
 		// No special handling: simply use no-arg constructor.
 		return instantiateBean(beanNamembd);
 	}

Determine candidate constructors to use for the given bean, checking all registered SmartInstantiationAwareBeanPostProcessors.

Parameters:
beanClass the raw class of the bean
beanName the name of the bean
Returns:
the candidate constructors, or null if none specified
Throws:
org.springframework.beans.BeansException in case of errors
See also:
org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors(java.lang.Class,java.lang.String)
 
 			throws BeansException {
 
 		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
 			for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 				BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 				if (beanProcessor instanceof SmartInstantiationAwareBeanPostProcessor) {
 					Constructor[] ctors = ibp.determineCandidateConstructors(beanClassbeanName);
 					if (ctors != null) {
 						return ctors;
 					}
 				}
 			}
 		}
 		return null;
 	}

Instantiate the given bean using its default constructor.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
Returns:
BeanWrapper for the new instance
 
 	protected BeanWrapper instantiateBean(String beanNameRootBeanDefinition mbd) {
 		try {
 			Object beanInstance = getInstantiationStrategy().instantiate(mbdbeanNamethis);
 			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
 			return bw;
 		}
 		catch (Throwable ex) {
 			throw new BeanCreationException(mbd.getResourceDescription(), beanName"Instantiation of bean failed"ex);
 		}
 	}

Instantiate the bean using a named factory method. The method may be static, if the mbd parameter specifies a class, rather than a factoryBean, or an instance variable on a factory object itself configured using Dependency Injection.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
explicitArgs argument values passed in programmatically via the getBean method, or null if none (-> use constructor argument values from bean definition)
Returns:
BeanWrapper for the new instance
See also:
AbstractBeanFactory.getBean(java.lang.String,java.lang.Object[])
 
 			String beanNameRootBeanDefinition mbdObject[] explicitArgs) {
 
 		ConstructorResolver constructorResolver =
 		return constructorResolver.instantiateUsingFactoryMethod(beanNamembdexplicitArgs);
 	}

"autowire constructor" (with constructor arguments by type) behavior. Also applied if explicit constructor argument values are specified, matching all remaining arguments with beans from the bean factory.

This corresponds to constructor injection: In this mode, a Spring bean factory is able to host components that expect constructor-based dependency resolution.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
ctors the chosen candidate constructors
explicitArgs argument values passed in programmatically via the getBean method, or null if none (-> use constructor argument values from bean definition)
Returns:
BeanWrapper for the new instance
 
 			String beanNameRootBeanDefinition mbdConstructor[] ctorsObject[] explicitArgs) {
 
 		ConstructorResolver constructorResolver =
 		return constructorResolver.autowireConstructor(beanNamembdctorsexplicitArgs);
 	}

Populate the bean instance in the given BeanWrapper with the property values from the bean definition.

Parameters:
beanName the name of the bean
mbd the bean definition for the bean
bw BeanWrapper with bean instance
 
 	protected void populateBean(String beanNameAbstractBeanDefinition mbdBeanWrapper bw) {
 
 		if (bw == null) {
 			if (!pvs.isEmpty()) {
 				throw new BeanCreationException(
 						mbd.getResourceDescription(), beanName"Cannot apply property values to null instance");
 			}
 			else {
 				// Skip property population phase for null instance.
 				return;
 			}
 		}
 
 		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
 		// state of the bean before properties are set. This can be used, for example,
 		// to support styles of field injection.
 		boolean continueWithPropertyPopulation = true;
 
 			for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
 				BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 				if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
 					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
 						continueWithPropertyPopulation = false;
 						break;
 					}
 				}
 			}
 		}
 
 		if (!continueWithPropertyPopulation) {
 			return;
 		}
 
 
 			// Add property values based on autowire by name if applicable.
 				autowireByName(beanNamembdbwnewPvs);
 			}
 
 			// Add property values based on autowire by type if applicable.
 				autowireByType(beanNamembdbwnewPvs);
 			}
 
 			pvs = newPvs;
 		}
 
 		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
 		boolean needsDepCheck = (mbd.getDependencyCheck() != .);
 
 		if (hasInstAwareBpps || needsDepCheck) {
 			if (hasInstAwareBpps) {
 				for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
 					BeanPostProcessor beanProcessor = (BeanPostProcessorit.next();
 					if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
 						pvs = ibp.postProcessPropertyValues(pvsfilteredPdsbw.getWrappedInstance(), beanName);
 						if (pvs == null) {
							return;
			if (needsDepCheck) {
				checkDependencies(beanNamembdfilteredPdspvs);
		applyPropertyValues(beanNamembdbwpvs);
	}

Fill in any missing property values with references to other beans in this factory if autowire is set to "byName".

Parameters:
beanName the name of the bean we're wiring up. Useful for debugging messages; not used functionally.
mbd bean definition to update through autowiring
bw BeanWrapper from which we can obtain information about the bean
pvs the PropertyValues to register wired objects with
	protected void autowireByName(
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbdbw);
		for (int i = 0; i < propertyNames.lengthi++) {
			String propertyName = propertyNames[i];
			if (containsBean(propertyName)) {
				Object bean = getBean(propertyName);
				pvs.addPropertyValue(propertyNamebean);
				registerDependentBean(propertyNamebeanName);
					.debug("Added autowiring by name from bean name '" + beanName +
						"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
			else {
					.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
	}

Abstract method defining "autowire by type" (bean properties by type) behavior.

This is like PicoContainer default, in which there must be exactly one bean of the property type in the bean factory. This makes bean factories simple to configure for small namespaces, but doesn't work as well as standard Spring behavior for bigger applications.

Parameters:
beanName the name of the bean to autowire by type
mbd the merged bean definition to update through autowiring
bw BeanWrapper from which we can obtain information about the bean
pvs the PropertyValues to register wired objects with
	protected void autowireByType(
		if (converter == null) {
			converter = bw;
		Set autowiredBeanNames = new LinkedHashSet(4);
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbdbw);
		for (int i = 0; i < propertyNames.lengthi++) {
			String propertyName = propertyNames[i];
			try {
				MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
				// Do not allow eager init for type matching in case of a prioritized post-processor.
				boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
				DependencyDescriptor desc = new DependencyDescriptor(methodParamfalseeager);
				Object autowiredArgument = resolveDependency(descbeanNameautowiredBeanNamesconverter);
				if (autowiredArgument != null) {
					pvs.addPropertyValue(propertyNameautowiredArgument);
				for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) {
					String autowiredBeanName = (Stringit.next();
					registerDependentBean(autowiredBeanNamebeanName);
						.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
								propertyName + "' to bean named '" + autowiredBeanName + "'");
				autowiredBeanNames.clear();
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanNamepropertyNameex);
	}


Return an array of non-simple bean properties that are unsatisfied. These are probably unsatisfied references to other beans in the factory. Does not include simple properties like primitives or Strings.

Parameters:
mbd the merged bean definition the bean was created with
bw the BeanWrapper the bean was created with
Returns:
an array of bean property names
See also:
org.springframework.beans.BeanUtils.isSimpleProperty(java.lang.Class)
		Set result = new TreeSet();
		for (int i = 0; i < pds.lengthi++) {
			if (pds[i].getWriteMethod() != null && !isExcludedFromDependencyCheck(pds[i]) &&
					!pvs.contains(pds[i].getName()) && !BeanUtils.isSimpleProperty(pds[i].getPropertyType())) {
				result.add(pds[i].getName());
		return StringUtils.toStringArray(result);
	}

Extract a filtered set of PropertyDescriptors from the given BeanWrapper, excluding ignored dependency types or properties defined on ignored dependency interfaces.

Parameters:
bw the BeanWrapper the bean was created with
Returns:
the filtered PropertyDescriptors
See also:
isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
		synchronized (this.) {
			if (filtered == null) {
				List pds = new LinkedList(Arrays.asList(bw.getPropertyDescriptors()));
				for (Iterator it = pds.iterator(); it.hasNext();) {
						it.remove();
				filtered = (PropertyDescriptor[]) pds.toArray(new PropertyDescriptor[pds.size()]);
			return filtered;
	}

Determine whether the given bean property is excluded from dependency checks.

This implementation excludes properties defined by CGLIB and properties whose type matches an ignored dependency type or which are defined by an ignored dependency interface.

Parameters:
pd the PropertyDescriptor of the bean property
Returns:
whether the bean property is excluded
See also:
ignoreDependencyType(java.lang.Class)
ignoreDependencyInterface(java.lang.Class)
		return (AutowireUtils.isExcludedFromDependencyCheck(pd) ||
	}

Perform a dependency check that all properties exposed have been set, if desired. Dependency checks can be objects (collaborating beans), simple (primitives and String), or all (both).

Parameters:
beanName the name of the bean
mbd the merged bean definition the bean was created with
pds the relevant property descriptors for the target bean
pvs the property values to be applied to the bean
See also:
isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
	protected void checkDependencies(
		int dependencyCheck = mbd.getDependencyCheck();
		for (int i = 0; i < pds.lengthi++) {
			if (pds[i].getWriteMethod() != null && !pvs.contains(pds[i].getName())) {
				boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType());
				boolean unsatisfied = (dependencyCheck == .) ||
					(isSimple && dependencyCheck == .) ||
					(!isSimple && dependencyCheck == .);
				if (unsatisfied) {
							mbd.getResourceDescription(), beanNamepds[i].getName(),
							"Set this property value or disable dependency checking for this bean.");
	}

Apply the given property values, resolving any runtime references to other beans in this bean factory. Must use deep copy, so we don't permanently modify this property.

Parameters:
beanName the bean name passed for better exception information
mbd the merged bean definition
bw the BeanWrapper wrapping the target object
pvs the new property values
	protected void applyPropertyValues(String beanNameBeanDefinition mbdBeanWrapper bwPropertyValues pvs) {
		if (pvs == null || pvs.isEmpty()) {
			return;
		MutablePropertyValues mpvs = null;
		List original = null;
		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValuespvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					return;
				catch (BeansException ex) {
							mbd.getResourceDescription(), beanName"Error setting property values"ex);
			original = mpvs.getPropertyValueList();
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		if (converter == null) {
			converter = bw;
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(thisbeanNamembdconverter);
		// Create a deep copy, resolving any references for values.
		List deepCopy = new ArrayList(original.size());
		boolean resolveNecessary = false;
		for (Iterator it = original.iterator(); it.hasNext();) {
			if (pv.isConverted()) {
				deepCopy.add(pv);
			else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pvoriginalValue);
				Object convertedValue = resolvedValue;
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					convertedValue = convertForProperty(resolvedValuepropertyNamebwconverter);
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				else if (originalValue instanceof TypedStringValue && convertible) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pvconvertedValue));
		if (mpvs != null && !resolveNecessary) {
		// Set our (possibly massaged) deep copy.
		try {
		catch (BeansException ex) {
					mbd.getResourceDescription(), beanName"Error setting property values"ex);
	}

Convert the given value for the specified target property.
	private Object convertForProperty(Object valueString propertyNameBeanWrapper bwTypeConverter converter) {
		if (converter instanceof BeanWrapperImpl) {
			return ((BeanWrapperImplconverter).convertForProperty(valuepropertyName);
		else {
			MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
			return converter.convertIfNecessary(valuepd.getPropertyType(), methodParam);
	}


Initialize the given bean instance, applying factory callbacks as well as init methods and bean post processors.

Called from createBean(java.lang.Class) for traditionally defined beans, and from initializeBean(java.lang.Object,java.lang.String) for existing bean instances.

Parameters:
beanName the bean name in the factory (for debugging purposes)
bean the new bean instance we may need to initialize
mbd the bean definition that the bean was created with (can also be null, if given an existing bean instance)
Returns:
the initialized bean instance (potentially wrapped)
See also:
org.springframework.beans.factory.BeanNameAware
org.springframework.beans.factory.BeanClassLoaderAware
org.springframework.beans.factory.BeanFactoryAware
applyBeanPostProcessorsBeforeInitialization(java.lang.Object,java.lang.String)
invokeInitMethods(java.lang.String,java.lang.Object,org.springframework.beans.factory.support.RootBeanDefinition)
applyBeanPostProcessorsAfterInitialization(java.lang.Object,java.lang.String)
	protected Object initializeBean(String beanNameObject beanRootBeanDefinition mbd) {
		if (bean instanceof BeanNameAware) {
			((BeanNameAwarebean).setBeanName(beanName);
		if (bean instanceof BeanClassLoaderAware) {
		if (bean instanceof BeanFactoryAware) {
		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBeanbeanName);
		try {
			invokeInitMethods(beanNamewrappedBeanmbd);
		catch (Throwable ex) {
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName"Invocation of init method failed"ex);
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBeanbeanName);
		return wrappedBean;
	}

Give a bean a chance to react now all its properties are set, and a chance to know about its owning bean factory (this object). This means checking whether the bean implements InitializingBean or defines a custom init method, and invoking the necessary callback(s) if it does.

Parameters:
beanName the bean name in the factory (for debugging purposes)
bean the new bean instance we may need to initialize
mbd the merged bean definition that the bean was created with (can also be null, if given an existing bean instance)
Throws:
java.lang.Throwable if thrown by init methods or by the invocation process
See also:
invokeCustomInitMethod(java.lang.String,java.lang.Object,java.lang.String,boolean)
	protected void invokeInitMethods(String beanNameObject beanRootBeanDefinition mbd)
			throws Throwable {
		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
				.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
		String initMethodName = (mbd != null ? mbd.getInitMethodName() : null);
		if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
				!mbd.isExternallyManagedInitMethod(initMethodName)) {
			invokeCustomInitMethod(beanNamebeaninitMethodNamembd.isEnforceInitMethod());
	}

Invoke the specified custom init method on the given bean. Called by invokeInitMethods.

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

Parameters:
beanName the bean name in the factory (for debugging purposes)
bean the new bean instance we may need to initialize
initMethodName the name of the custom init method
enforceInitMethod indicates whether the defined init method needs to exist
See also:
invokeInitMethods(java.lang.String,java.lang.Object,org.springframework.beans.factory.support.RootBeanDefinition)
	protected void invokeCustomInitMethod(
			String beanNameObject beanString initMethodNameboolean enforceInitMethodthrows Throwable {
		Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodNamenull);
		if (initMethod == null) {
			if (enforceInitMethod) {
				throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
						"' on bean with name '" + beanName + "'");
			else {
					.debug("No default init method named '" + initMethodName +
							"' found on bean with name '" + beanName + "'");
				// Ignore non-existent default lifecycle methods.
				return;
			.debug("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
		ReflectionUtils.makeAccessible(initMethod);
		try {
			initMethod.invoke(bean, (Object[]) null);
	}


Applies the postProcessAfterInitialization callback of all registered BeanPostProcessors, giving them a chance to post-process the object obtained from FactoryBeans (for example, to auto-proxy them).

	protected Object postProcessObjectFromFactoryBean(Object objectString beanName) {
	}

Overridden to clear FactoryBean instance cache as well.
	protected void removeSingleton(String beanName) {
		super.removeSingleton(beanName);
New to GrepCode? Check out our FAQ X