View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.beans.factory.support;
18  
19  import java.beans.PropertyDescriptor;
20  import java.lang.reflect.Constructor;
21  import java.lang.reflect.InvocationTargetException;
22  import java.lang.reflect.Method;
23  import java.lang.reflect.Modifier;
24  import java.security.AccessController;
25  import java.security.PrivilegedAction;
26  import java.security.PrivilegedActionException;
27  import java.security.PrivilegedExceptionAction;
28  import java.util.ArrayList;
29  import java.util.Arrays;
30  import java.util.Collection;
31  import java.util.HashSet;
32  import java.util.Iterator;
33  import java.util.LinkedHashSet;
34  import java.util.LinkedList;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Set;
38  import java.util.TreeSet;
39  import java.util.concurrent.ConcurrentHashMap;
40  import java.util.concurrent.ConcurrentMap;
41  
42  import org.springframework.beans.BeanUtils;
43  import org.springframework.beans.BeanWrapper;
44  import org.springframework.beans.BeanWrapperImpl;
45  import org.springframework.beans.BeansException;
46  import org.springframework.beans.MutablePropertyValues;
47  import org.springframework.beans.PropertyAccessorUtils;
48  import org.springframework.beans.PropertyValue;
49  import org.springframework.beans.PropertyValues;
50  import org.springframework.beans.TypeConverter;
51  import org.springframework.beans.factory.Aware;
52  import org.springframework.beans.factory.BeanClassLoaderAware;
53  import org.springframework.beans.factory.BeanCreationException;
54  import org.springframework.beans.factory.BeanCurrentlyInCreationException;
55  import org.springframework.beans.factory.BeanDefinitionStoreException;
56  import org.springframework.beans.factory.BeanFactory;
57  import org.springframework.beans.factory.BeanFactoryAware;
58  import org.springframework.beans.factory.BeanNameAware;
59  import org.springframework.beans.factory.FactoryBean;
60  import org.springframework.beans.factory.InitializingBean;
61  import org.springframework.beans.factory.ObjectFactory;
62  import org.springframework.beans.factory.UnsatisfiedDependencyException;
63  import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
64  import org.springframework.beans.factory.config.BeanDefinition;
65  import org.springframework.beans.factory.config.BeanPostProcessor;
66  import org.springframework.beans.factory.config.ConfigurableBeanFactory;
67  import org.springframework.beans.factory.config.ConstructorArgumentValues;
68  import org.springframework.beans.factory.config.DependencyDescriptor;
69  import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
70  import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
71  import org.springframework.beans.factory.config.TypedStringValue;
72  import org.springframework.core.DefaultParameterNameDiscoverer;
73  import org.springframework.core.GenericTypeResolver;
74  import org.springframework.core.MethodParameter;
75  import org.springframework.core.ParameterNameDiscoverer;
76  import org.springframework.core.PriorityOrdered;
77  import org.springframework.util.ClassUtils;
78  import org.springframework.util.ObjectUtils;
79  import org.springframework.util.ReflectionUtils;
80  import org.springframework.util.StringUtils;
81  
82  /**
83   * Abstract bean factory superclass that implements default bean creation,
84   * with the full capabilities specified by the {@link RootBeanDefinition} class.
85   * Implements the {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory}
86   * interface in addition to AbstractBeanFactory's {@link #createBean} method.
87   *
88   * <p>Provides bean creation (with constructor resolution), property population,
89   * wiring (including autowiring), and initialization. Handles runtime bean
90   * references, resolves managed collections, calls initialization methods, etc.
91   * Supports autowiring constructors, properties by name, and properties by type.
92   *
93   * <p>The main template method to be implemented by subclasses is
94   * {@link #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)},
95   * used for autowiring by type. In case of a factory which is capable of searching
96   * its bean definitions, matching beans will typically be implemented through such
97   * a search. For other factory styles, simplified matching algorithms can be implemented.
98   *
99   * <p>Note that this class does <i>not</i> assume or implement bean definition
100  * registry capabilities. See {@link DefaultListableBeanFactory} for an implementation
101  * of the {@link org.springframework.beans.factory.ListableBeanFactory} and
102  * {@link BeanDefinitionRegistry} interfaces, which represent the API and SPI
103  * view of such a factory, respectively.
104  *
105  * @author Rod Johnson
106  * @author Juergen Hoeller
107  * @author Rob Harrop
108  * @author Mark Fisher
109  * @author Costin Leau
110  * @author Chris Beams
111  * @author Sam Brannen
112  * @since 13.02.2004
113  * @see RootBeanDefinition
114  * @see DefaultListableBeanFactory
115  * @see BeanDefinitionRegistry
116  */
117 public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
118 		implements AutowireCapableBeanFactory {
119 
120 	/** Strategy for creating bean instances */
121 	private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
122 
123 	/** Resolver strategy for method parameter names */
124 	private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
125 
126 	/** Whether to automatically try to resolve circular references between beans */
127 	private boolean allowCircularReferences = true;
128 
129 	/**
130 	 * Whether to resort to injecting a raw bean instance in case of circular reference,
131 	 * even if the injected bean eventually got wrapped.
132 	 */
133 	private boolean allowRawInjectionDespiteWrapping = false;
134 
135 	/**
136 	 * Dependency types to ignore on dependency check and autowire, as Set of
137 	 * Class objects: for example, String. Default is none.
138 	 */
139 	private final Set<Class<?>> ignoredDependencyTypes = new HashSet<Class<?>>();
140 
141 	/**
142 	 * Dependency interfaces to ignore on dependency check and autowire, as Set of
143 	 * Class objects. By default, only the BeanFactory interface is ignored.
144 	 */
145 	private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<Class<?>>();
146 
147 	/** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
148 	private final Map<String, BeanWrapper> factoryBeanInstanceCache =
149 			new ConcurrentHashMap<String, BeanWrapper>(16);
150 
151 	/** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */
152 	private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
153 			new ConcurrentHashMap<Class<?>, PropertyDescriptor[]>(64);
154 
155 
156 	/**
157 	 * Create a new AbstractAutowireCapableBeanFactory.
158 	 */
159 	public AbstractAutowireCapableBeanFactory() {
160 		super();
161 		ignoreDependencyInterface(BeanNameAware.class);
162 		ignoreDependencyInterface(BeanFactoryAware.class);
163 		ignoreDependencyInterface(BeanClassLoaderAware.class);
164 	}
165 
166 	/**
167 	 * Create a new AbstractAutowireCapableBeanFactory with the given parent.
168 	 * @param parentBeanFactory parent bean factory, or {@code null} if none
169 	 */
170 	public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
171 		this();
172 		setParentBeanFactory(parentBeanFactory);
173 	}
174 
175 
176 	/**
177 	 * Set the instantiation strategy to use for creating bean instances.
178 	 * Default is CglibSubclassingInstantiationStrategy.
179 	 * @see CglibSubclassingInstantiationStrategy
180 	 */
181 	public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
182 		this.instantiationStrategy = instantiationStrategy;
183 	}
184 
185 	/**
186 	 * Return the instantiation strategy to use for creating bean instances.
187 	 */
188 	protected InstantiationStrategy getInstantiationStrategy() {
189 		return this.instantiationStrategy;
190 	}
191 
192 	/**
193 	 * Set the ParameterNameDiscoverer to use for resolving method parameter
194 	 * names if needed (e.g. for constructor names).
195 	 * <p>Default is a {@link DefaultParameterNameDiscoverer}.
196 	 */
197 	public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
198 		this.parameterNameDiscoverer = parameterNameDiscoverer;
199 	}
200 
201 	/**
202 	 * Return the ParameterNameDiscoverer to use for resolving method parameter
203 	 * names if needed.
204 	 */
205 	protected ParameterNameDiscoverer getParameterNameDiscoverer() {
206 		return this.parameterNameDiscoverer;
207 	}
208 
209 	/**
210 	 * Set whether to allow circular references between beans - and automatically
211 	 * try to resolve them.
212 	 * <p>Note that circular reference resolution means that one of the involved beans
213 	 * will receive a reference to another bean that is not fully initialized yet.
214 	 * This can lead to subtle and not-so-subtle side effects on initialization;
215 	 * it does work fine for many scenarios, though.
216 	 * <p>Default is "true". Turn this off to throw an exception when encountering
217 	 * a circular reference, disallowing them completely.
218 	 * <p><b>NOTE:</b> It is generally recommended to not rely on circular references
219 	 * between your beans. Refactor your application logic to have the two beans
220 	 * involved delegate to a third bean that encapsulates their common logic.
221 	 */
222 	public void setAllowCircularReferences(boolean allowCircularReferences) {
223 		this.allowCircularReferences = allowCircularReferences;
224 	}
225 
226 	/**
227 	 * Set whether to allow the raw injection of a bean instance into some other
228 	 * bean's property, despite the injected bean eventually getting wrapped
229 	 * (for example, through AOP auto-proxying).
230 	 * <p>This will only be used as a last resort in case of a circular reference
231 	 * that cannot be resolved otherwise: essentially, preferring a raw instance
232 	 * getting injected over a failure of the entire bean wiring process.
233 	 * <p>Default is "false", as of Spring 2.0. Turn this on to allow for non-wrapped
234 	 * raw beans injected into some of your references, which was Spring 1.2's
235 	 * (arguably unclean) default behavior.
236 	 * <p><b>NOTE:</b> It is generally recommended to not rely on circular references
237 	 * between your beans, in particular with auto-proxying involved.
238 	 * @see #setAllowCircularReferences
239 	 */
240 	public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
241 		this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
242 	}
243 
244 	/**
245 	 * Ignore the given dependency type for autowiring:
246 	 * for example, String. Default is none.
247 	 */
248 	public void ignoreDependencyType(Class<?> type) {
249 		this.ignoredDependencyTypes.add(type);
250 	}
251 
252 	/**
253 	 * Ignore the given dependency interface for autowiring.
254 	 * <p>This will typically be used by application contexts to register
255 	 * dependencies that are resolved in other ways, like BeanFactory through
256 	 * BeanFactoryAware or ApplicationContext through ApplicationContextAware.
257 	 * <p>By default, only the BeanFactoryAware interface is ignored.
258 	 * For further types to ignore, invoke this method for each type.
259 	 * @see org.springframework.beans.factory.BeanFactoryAware
260 	 * @see org.springframework.context.ApplicationContextAware
261 	 */
262 	public void ignoreDependencyInterface(Class<?> ifc) {
263 		this.ignoredDependencyInterfaces.add(ifc);
264 	}
265 
266 	@Override
267 	public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
268 		super.copyConfigurationFrom(otherFactory);
269 		if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
270 			AbstractAutowireCapableBeanFactory otherAutowireFactory =
271 					(AbstractAutowireCapableBeanFactory) otherFactory;
272 			this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
273 			this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
274 			this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
275 			this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
276 		}
277 	}
278 
279 
280 	//-------------------------------------------------------------------------
281 	// Typical methods for creating and populating external bean instances
282 	//-------------------------------------------------------------------------
283 
284 	@Override
285 	@SuppressWarnings("unchecked")
286 	public <T> T createBean(Class<T> beanClass) throws BeansException {
287 		// Use prototype bean definition, to avoid registering bean as dependent bean.
288 		RootBeanDefinition bd = new RootBeanDefinition(beanClass);
289 		bd.setScope(SCOPE_PROTOTYPE);
290 		bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
291 		return (T) createBean(beanClass.getName(), bd, null);
292 	}
293 
294 	@Override
295 	public void autowireBean(Object existingBean) {
296 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
297 		RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
298 		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
299 		bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
300 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
301 		initBeanWrapper(bw);
302 		populateBean(bd.getBeanClass().getName(), bd, bw);
303 	}
304 
305 	@Override
306 	public Object configureBean(Object existingBean, String beanName) throws BeansException {
307 		markBeanAsCreated(beanName);
308 		BeanDefinition mbd = getMergedBeanDefinition(beanName);
309 		RootBeanDefinition bd = null;
310 		if (mbd instanceof RootBeanDefinition) {
311 			RootBeanDefinition rbd = (RootBeanDefinition) mbd;
312 			bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
313 		}
314 		if (!mbd.isPrototype()) {
315 			if (bd == null) {
316 				bd = new RootBeanDefinition(mbd);
317 			}
318 			bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
319 			bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
320 		}
321 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
322 		initBeanWrapper(bw);
323 		populateBean(beanName, bd, bw);
324 		return initializeBean(beanName, existingBean, bd);
325 	}
326 
327 	@Override
328 	public Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException {
329 		return resolveDependency(descriptor, beanName, null, null);
330 	}
331 
332 
333 	//-------------------------------------------------------------------------
334 	// Specialized methods for fine-grained control over the bean lifecycle
335 	//-------------------------------------------------------------------------
336 
337 	@Override
338 	public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
339 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
340 		RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
341 		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
342 		return createBean(beanClass.getName(), bd, null);
343 	}
344 
345 	@Override
346 	public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
347 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
348 		final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
349 		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
350 		if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
351 			return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
352 		}
353 		else {
354 			Object bean;
355 			final BeanFactory parent = this;
356 			if (System.getSecurityManager() != null) {
357 				bean = AccessController.doPrivileged(new PrivilegedAction<Object>() {
358 					@Override
359 					public Object run() {
360 						return getInstantiationStrategy().instantiate(bd, null, parent);
361 					}
362 				}, getAccessControlContext());
363 			}
364 			else {
365 				bean = getInstantiationStrategy().instantiate(bd, null, parent);
366 			}
367 			populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
368 			return bean;
369 		}
370 	}
371 
372 	@Override
373 	public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
374 			throws BeansException {
375 
376 		if (autowireMode == AUTOWIRE_CONSTRUCTOR) {
377 			throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance");
378 		}
379 		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
380 		RootBeanDefinition bd =
381 				new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck);
382 		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
383 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
384 		initBeanWrapper(bw);
385 		populateBean(bd.getBeanClass().getName(), bd, bw);
386 	}
387 
388 	@Override
389 	public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
390 		markBeanAsCreated(beanName);
391 		BeanDefinition bd = getMergedBeanDefinition(beanName);
392 		BeanWrapper bw = new BeanWrapperImpl(existingBean);
393 		initBeanWrapper(bw);
394 		applyPropertyValues(beanName, bd, bw, bd.getPropertyValues());
395 	}
396 
397 	@Override
398 	public Object initializeBean(Object existingBean, String beanName) {
399 		return initializeBean(beanName, existingBean, null);
400 	}
401 
402 	@Override
403 	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
404 			throws BeansException {
405 
406 		Object result = existingBean;
407 		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
408 			result = beanProcessor.postProcessBeforeInitialization(result, beanName);
409 			if (result == null) {
410 				return result;
411 			}
412 		}
413 		return result;
414 	}
415 
416 	@Override
417 	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
418 			throws BeansException {
419 
420 		Object result = existingBean;
421 		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
422 			result = beanProcessor.postProcessAfterInitialization(result, beanName);
423 			if (result == null) {
424 				return result;
425 			}
426 		}
427 		return result;
428 	}
429 
430 	@Override
431 	public void destroyBean(Object existingBean) {
432 		new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
433 	}
434 
435 
436 	//---------------------------------------------------------------------
437 	// Implementation of relevant AbstractBeanFactory template methods
438 	//---------------------------------------------------------------------
439 
440 	/**
441 	 * Central method of this class: creates a bean instance,
442 	 * populates the bean instance, applies post-processors, etc.
443 	 * @see #doCreateBean
444 	 */
445 	@Override
446 	protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
447 			throws BeanCreationException {
448 
449 		if (logger.isDebugEnabled()) {
450 			logger.debug("Creating instance of bean '" + beanName + "'");
451 		}
452 		// Make sure bean class is actually resolved at this point.
453 		resolveBeanClass(mbd, beanName);
454 
455 		// Prepare method overrides.
456 		try {
457 			mbd.prepareMethodOverrides();
458 		}
459 		catch (BeanDefinitionValidationException ex) {
460 			throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
461 					beanName, "Validation of method overrides failed", ex);
462 		}
463 
464 		try {
465 			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
466 			Object bean = resolveBeforeInstantiation(beanName, mbd);
467 			if (bean != null) {
468 				return bean;
469 			}
470 		}
471 		catch (Throwable ex) {
472 			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
473 					"BeanPostProcessor before instantiation of bean failed", ex);
474 		}
475 
476 		Object beanInstance = doCreateBean(beanName, mbd, args);
477 		if (logger.isDebugEnabled()) {
478 			logger.debug("Finished creating instance of bean '" + beanName + "'");
479 		}
480 		return beanInstance;
481 	}
482 
483 	/**
484 	 * Actually create the specified bean. Pre-creation processing has already happened
485 	 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
486 	 * <p>Differentiates between default bean instantiation, use of a
487 	 * factory method, and autowiring a constructor.
488 	 * @param beanName the name of the bean
489 	 * @param mbd the merged bean definition for the bean
490 	 * @param args explicit arguments to use for constructor or factory method invocation
491 	 * @return a new instance of the bean
492 	 * @throws BeanCreationException if the bean could not be created
493 	 * @see #instantiateBean
494 	 * @see #instantiateUsingFactoryMethod
495 	 * @see #autowireConstructor
496 	 */
497 	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
498 		// Instantiate the bean.
499 		BeanWrapper instanceWrapper = null;
500 		if (mbd.isSingleton()) {
501 			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
502 		}
503 		if (instanceWrapper == null) {
504 			instanceWrapper = createBeanInstance(beanName, mbd, args);
505 		}
506 		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
507 		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
508 
509 		// Allow post-processors to modify the merged bean definition.
510 		synchronized (mbd.postProcessingLock) {
511 			if (!mbd.postProcessed) {
512 				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
513 				mbd.postProcessed = true;
514 			}
515 		}
516 
517 		// Eagerly cache singletons to be able to resolve circular references
518 		// even when triggered by lifecycle interfaces like BeanFactoryAware.
519 		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
520 				isSingletonCurrentlyInCreation(beanName));
521 		if (earlySingletonExposure) {
522 			if (logger.isDebugEnabled()) {
523 				logger.debug("Eagerly caching bean '" + beanName +
524 						"' to allow for resolving potential circular references");
525 			}
526 			addSingletonFactory(beanName, new ObjectFactory<Object>() {
527 				@Override
528 				public Object getObject() throws BeansException {
529 					return getEarlyBeanReference(beanName, mbd, bean);
530 				}
531 			});
532 		}
533 
534 		// Initialize the bean instance.
535 		Object exposedObject = bean;
536 		try {
537 			populateBean(beanName, mbd, instanceWrapper);
538 			if (exposedObject != null) {
539 				exposedObject = initializeBean(beanName, exposedObject, mbd);
540 			}
541 		}
542 		catch (Throwable ex) {
543 			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
544 				throw (BeanCreationException) ex;
545 			}
546 			else {
547 				throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
548 			}
549 		}
550 
551 		if (earlySingletonExposure) {
552 			Object earlySingletonReference = getSingleton(beanName, false);
553 			if (earlySingletonReference != null) {
554 				if (exposedObject == bean) {
555 					exposedObject = earlySingletonReference;
556 				}
557 				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
558 					String[] dependentBeans = getDependentBeans(beanName);
559 					Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
560 					for (String dependentBean : dependentBeans) {
561 						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
562 							actualDependentBeans.add(dependentBean);
563 						}
564 					}
565 					if (!actualDependentBeans.isEmpty()) {
566 						throw new BeanCurrentlyInCreationException(beanName,
567 								"Bean with name '" + beanName + "' has been injected into other beans [" +
568 								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
569 								"] in its raw version as part of a circular reference, but has eventually been " +
570 								"wrapped. This means that said other beans do not use the final version of the " +
571 								"bean. This is often the result of over-eager type matching - consider using " +
572 								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
573 					}
574 				}
575 			}
576 		}
577 
578 		// Register bean as disposable.
579 		try {
580 			registerDisposableBeanIfNecessary(beanName, bean, mbd);
581 		}
582 		catch (BeanDefinitionValidationException ex) {
583 			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
584 		}
585 
586 		return exposedObject;
587 	}
588 
589 	@Override
590 	protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
591 		Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
592 
593 		// Apply SmartInstantiationAwareBeanPostProcessors to predict the
594 		// eventual type after a before-instantiation shortcut.
595 		if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
596 			for (BeanPostProcessor bp : getBeanPostProcessors()) {
597 				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
598 					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
599 					Class<?> predicted = ibp.predictBeanType(targetType, beanName);
600 					if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) ||
601 							FactoryBean.class.isAssignableFrom(predicted))) {
602 						return predicted;
603 					}
604 				}
605 			}
606 		}
607 		return targetType;
608 	}
609 
610 	/**
611 	 * Determine the target type for the given bean definition.
612 	 * @param beanName the name of the bean (for error handling purposes)
613 	 * @param mbd the merged bean definition for the bean
614 	 * @param typesToMatch the types to match in case of internal type matching purposes
615 	 * (also signals that the returned {@code Class} will never be exposed to application code)
616 	 * @return the type for the bean if determinable, or {@code null} otherwise
617 	 */
618 	protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
619 		Class<?> targetType = mbd.getTargetType();
620 		if (targetType == null) {
621 			targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
622 					resolveBeanClass(mbd, beanName, typesToMatch));
623 			if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
624 				mbd.setTargetType(targetType);
625 			}
626 		}
627 		return targetType;
628 	}
629 
630 	/**
631 	 * Determine the target type for the given bean definition which is based on
632 	 * a factory method. Only called if there is no singleton instance registered
633 	 * for the target bean already.
634 	 * <p>This implementation determines the type matching {@link #createBean}'s
635 	 * different creation strategies. As far as possible, we'll perform static
636 	 * type checking to avoid creation of the target bean.
637 	 * @param beanName the name of the bean (for error handling purposes)
638 	 * @param mbd the merged bean definition for the bean
639 	 * @param typesToMatch the types to match in case of internal type matching purposes
640 	 * (also signals that the returned {@code Class} will never be exposed to application code)
641 	 * @return the type for the bean if determinable, or {@code null} otherwise
642 	 * @see #createBean
643 	 */
644 	protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
645 		Class<?> preResolved = mbd.resolvedFactoryMethodReturnType;
646 		if (preResolved != null) {
647 			return preResolved;
648 		}
649 
650 		Class<?> factoryClass;
651 		boolean isStatic = true;
652 
653 		String factoryBeanName = mbd.getFactoryBeanName();
654 		if (factoryBeanName != null) {
655 			if (factoryBeanName.equals(beanName)) {
656 				throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
657 						"factory-bean reference points back to the same bean definition");
658 			}
659 			// Check declared factory method return type on factory class.
660 			factoryClass = getType(factoryBeanName);
661 			isStatic = false;
662 		}
663 		else {
664 			// Check declared factory method return type on bean class.
665 			factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
666 		}
667 
668 		if (factoryClass == null) {
669 			return null;
670 		}
671 
672 		// If all factory methods have the same return type, return that type.
673 		// Can't clearly figure out exact method due to type converting / autowiring!
674 		Class<?> commonType = null;
675 		boolean cache = false;
676 		int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount();
677 		Method[] candidates = ReflectionUtils.getUniqueDeclaredMethods(factoryClass);
678 		for (Method factoryMethod : candidates) {
679 			if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
680 					factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
681 					factoryMethod.getParameterTypes().length >= minNrOfArgs) {
682 				// No declared type variables to inspect, so just process the standard return type.
683 				if (factoryMethod.getTypeParameters().length > 0) {
684 					try {
685 						// Fully resolve parameter names and argument values.
686 						Class<?>[] paramTypes = factoryMethod.getParameterTypes();
687 						String[] paramNames = null;
688 						ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
689 						if (pnd != null) {
690 							paramNames = pnd.getParameterNames(factoryMethod);
691 						}
692 						ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
693 						Set<ConstructorArgumentValues.ValueHolder> usedValueHolders =
694 								new HashSet<ConstructorArgumentValues.ValueHolder>(paramTypes.length);
695 						Object[] args = new Object[paramTypes.length];
696 						for (int i = 0; i < args.length; i++) {
697 							ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(
698 									i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
699 							if (valueHolder == null) {
700 								valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
701 							}
702 							if (valueHolder != null) {
703 								args[i] = valueHolder.getValue();
704 								usedValueHolders.add(valueHolder);
705 							}
706 						}
707 						Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(
708 								factoryMethod, args, getBeanClassLoader());
709 						if (returnType != null) {
710 							cache = true;
711 							commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
712 						}
713 					}
714 					catch (Throwable ex) {
715 						if (logger.isDebugEnabled()) {
716 							logger.debug("Failed to resolve generic return type for factory method: " + ex);
717 						}
718 					}
719 				}
720 				else {
721 					commonType = ClassUtils.determineCommonAncestor(factoryMethod.getReturnType(), commonType);
722 				}
723 			}
724 		}
725 
726 		if (commonType != null) {
727 			// Clear return type found: all factory methods return same type.
728 			if (cache) {
729 				mbd.resolvedFactoryMethodReturnType = commonType;
730 			}
731 			return commonType;
732 		}
733 		else {
734 			// Ambiguous return types found: return null to indicate "not determinable".
735 			return null;
736 		}
737 	}
738 
739 	/**
740 	 * This implementation attempts to query the FactoryBean's generic parameter metadata
741 	 * if present to determine the object type. If not present, i.e. the FactoryBean is
742 	 * declared as a raw type, checks the FactoryBean's {@code getObjectType} method
743 	 * on a plain instance of the FactoryBean, without bean properties applied yet.
744 	 * If this doesn't return a type yet, a full creation of the FactoryBean is
745 	 * used as fallback (through delegation to the superclass's implementation).
746 	 * <p>The shortcut check for a FactoryBean is only applied in case of a singleton
747 	 * FactoryBean. If the FactoryBean instance itself is not kept as singleton,
748 	 * it will be fully created to check the type of its exposed object.
749 	 */
750 	@Override
751 	protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
752 		class Holder { Class<?> value = null; }
753 		final Holder objectType = new Holder();
754 		String factoryBeanName = mbd.getFactoryBeanName();
755 		final String factoryMethodName = mbd.getFactoryMethodName();
756 
757 		if (factoryBeanName != null) {
758 			if (factoryMethodName != null) {
759 				// Try to obtain the FactoryBean's object type without instantiating it at all.
760 				BeanDefinition fbDef = getBeanDefinition(factoryBeanName);
761 				if (fbDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) fbDef).hasBeanClass()) {
762 					// CGLIB subclass methods hide generic parameters; look at the original user class.
763 					Class<?> fbClass = ClassUtils.getUserClass(((AbstractBeanDefinition) fbDef).getBeanClass());
764 					// Find the given factory method, taking into account that in the case of
765 					// @Bean methods, there may be parameters present.
766 					ReflectionUtils.doWithMethods(fbClass,
767 							new ReflectionUtils.MethodCallback() {
768 								@Override
769 								public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
770 									if (method.getName().equals(factoryMethodName) &&
771 											FactoryBean.class.isAssignableFrom(method.getReturnType())) {
772 										objectType.value = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class);
773 									}
774 								}
775 							});
776 					if (objectType.value != null && !Object.class.equals(objectType.value)) {
777 						return objectType.value;
778 					}
779 				}
780 			}
781 			// If not resolvable above and the referenced factory bean doesn't exist yet,
782 			// exit here - we don't want to force the creation of another bean just to
783 			// obtain a FactoryBean's object type...
784 			if (!isBeanEligibleForMetadataCaching(factoryBeanName)) {
785 				return null;
786 			}
787 		}
788 
789 		FactoryBean<?> fb = (mbd.isSingleton() ?
790 				getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
791 				getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));
792 
793 		if (fb != null) {
794 			// Try to obtain the FactoryBean's object type from this early stage of the instance.
795 			objectType.value = getTypeForFactoryBean(fb);
796 			if (objectType.value != null) {
797 				return objectType.value;
798 			}
799 		}
800 
801 		// No type found - fall back to full creation of the FactoryBean instance.
802 		return super.getTypeForFactoryBean(beanName, mbd);
803 	}
804 
805 	/**
806 	 * Obtain a reference for early access to the specified bean,
807 	 * typically for the purpose of resolving a circular reference.
808 	 * @param beanName the name of the bean (for error handling purposes)
809 	 * @param mbd the merged bean definition for the bean
810 	 * @param bean the raw bean instance
811 	 * @return the object to expose as bean reference
812 	 */
813 	protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
814 		Object exposedObject = bean;
815 		if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
816 			for (BeanPostProcessor bp : getBeanPostProcessors()) {
817 				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
818 					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
819 					exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
820 					if (exposedObject == null) {
821 						return exposedObject;
822 					}
823 				}
824 			}
825 		}
826 		return exposedObject;
827 	}
828 
829 
830 	//---------------------------------------------------------------------
831 	// Implementation methods
832 	//---------------------------------------------------------------------
833 
834 	/**
835 	 * Obtain a "shortcut" singleton FactoryBean instance to use for a
836 	 * {@code getObjectType()} call, without full initialization
837 	 * of the FactoryBean.
838 	 * @param beanName the name of the bean
839 	 * @param mbd the bean definition for the bean
840 	 * @return the FactoryBean instance, or {@code null} to indicate
841 	 * that we couldn't obtain a shortcut FactoryBean instance
842 	 */
843 	private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
844 		synchronized (getSingletonMutex()) {
845 			BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
846 			if (bw != null) {
847 				return (FactoryBean<?>) bw.getWrappedInstance();
848 			}
849 			if (isSingletonCurrentlyInCreation(beanName) ||
850 					(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
851 				return null;
852 			}
853 			Object instance = null;
854 			try {
855 				// Mark this bean as currently in creation, even if just partially.
856 				beforeSingletonCreation(beanName);
857 				// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
858 				instance = resolveBeforeInstantiation(beanName, mbd);
859 				if (instance == null) {
860 					bw = createBeanInstance(beanName, mbd, null);
861 					instance = bw.getWrappedInstance();
862 				}
863 			}
864 			finally {
865 				// Finished partial creation of this bean.
866 				afterSingletonCreation(beanName);
867 			}
868 			FactoryBean<?> fb = getFactoryBean(beanName, instance);
869 			if (bw != null) {
870 				this.factoryBeanInstanceCache.put(beanName, bw);
871 			}
872 			return fb;
873 		}
874 	}
875 
876 	/**
877 	 * Obtain a "shortcut" non-singleton FactoryBean instance to use for a
878 	 * {@code getObjectType()} call, without full initialization
879 	 * of the FactoryBean.
880 	 * @param beanName the name of the bean
881 	 * @param mbd the bean definition for the bean
882 	 * @return the FactoryBean instance, or {@code null} to indicate
883 	 * that we couldn't obtain a shortcut FactoryBean instance
884 	 */
885 	private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
886 		if (isPrototypeCurrentlyInCreation(beanName)) {
887 			return null;
888 		}
889 		Object instance = null;
890 		try {
891 			// Mark this bean as currently in creation, even if just partially.
892 			beforePrototypeCreation(beanName);
893 			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
894 			instance = resolveBeforeInstantiation(beanName, mbd);
895 			if (instance == null) {
896 				BeanWrapper bw = createBeanInstance(beanName, mbd, null);
897 				instance = bw.getWrappedInstance();
898 			}
899 		}
900 		catch (BeanCreationException ex) {
901 			// Can only happen when getting a FactoryBean.
902 			if (logger.isDebugEnabled()) {
903 				logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex);
904 			}
905 			onSuppressedException(ex);
906 			return null;
907 		}
908 		finally {
909 			// Finished partial creation of this bean.
910 			afterPrototypeCreation(beanName);
911 		}
912 		return getFactoryBean(beanName, instance);
913 	}
914 
915 	/**
916 	 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
917 	 * invoking their {@code postProcessMergedBeanDefinition} methods.
918 	 * @param mbd the merged bean definition for the bean
919 	 * @param beanType the actual type of the managed bean instance
920 	 * @param beanName the name of the bean
921 	 * @throws BeansException if any post-processing failed
922 	 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
923 	 */
924 	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
925 			throws BeansException {
926 
927 		try {
928 			for (BeanPostProcessor bp : getBeanPostProcessors()) {
929 				if (bp instanceof MergedBeanDefinitionPostProcessor) {
930 					MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
931 					bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
932 				}
933 			}
934 		}
935 		catch (Exception ex) {
936 			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
937 					"Post-processing failed of bean type [" + beanType + "] failed", ex);
938 		}
939 	}
940 
941 	/**
942 	 * Apply before-instantiation post-processors, resolving whether there is a
943 	 * before-instantiation shortcut for the specified bean.
944 	 * @param beanName the name of the bean
945 	 * @param mbd the bean definition for the bean
946 	 * @return the shortcut-determined bean instance, or {@code null} if none
947 	 */
948 	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
949 		Object bean = null;
950 		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
951 			// Make sure bean class is actually resolved at this point.
952 			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
953 				Class<?> targetType = determineTargetType(beanName, mbd);
954 				if (targetType != null) {
955 					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
956 					if (bean != null) {
957 						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
958 					}
959 				}
960 			}
961 			mbd.beforeInstantiationResolved = (bean != null);
962 		}
963 		return bean;
964 	}
965 
966 	/**
967 	 * Apply InstantiationAwareBeanPostProcessors to the specified bean definition
968 	 * (by class and name), invoking their {@code postProcessBeforeInstantiation} methods.
969 	 * <p>Any returned object will be used as the bean instead of actually instantiating
970 	 * the target bean. A {@code null} return value from the post-processor will
971 	 * result in the target bean being instantiated.
972 	 * @param beanClass the class of the bean to be instantiated
973 	 * @param beanName the name of the bean
974 	 * @return the bean object to use instead of a default instance of the target bean, or {@code null}
975 	 * @throws BeansException if any post-processing failed
976 	 * @see InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
977 	 */
978 	protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)
979 			throws BeansException {
980 
981 		for (BeanPostProcessor bp : getBeanPostProcessors()) {
982 			if (bp instanceof InstantiationAwareBeanPostProcessor) {
983 				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
984 				Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
985 				if (result != null) {
986 					return result;
987 				}
988 			}
989 		}
990 		return null;
991 	}
992 
993 	/**
994 	 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
995 	 * factory method, constructor autowiring, or simple instantiation.
996 	 * @param beanName the name of the bean
997 	 * @param mbd the bean definition for the bean
998 	 * @param args explicit arguments to use for constructor or factory method invocation
999 	 * @return BeanWrapper for the new instance
1000 	 * @see #instantiateUsingFactoryMethod
1001 	 * @see #autowireConstructor
1002 	 * @see #instantiateBean
1003 	 */
1004 	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
1005 		// Make sure bean class is actually resolved at this point.
1006 		Class<?> beanClass = resolveBeanClass(mbd, beanName);
1007 
1008 		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
1009 			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
1010 					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
1011 		}
1012 
1013 		if (mbd.getFactoryMethodName() != null)  {
1014 			return instantiateUsingFactoryMethod(beanName, mbd, args);
1015 		}
1016 
1017 		// Shortcut when re-creating the same bean...
1018 		boolean resolved = false;
1019 		boolean autowireNecessary = false;
1020 		if (args == null) {
1021 			synchronized (mbd.constructorArgumentLock) {
1022 				if (mbd.resolvedConstructorOrFactoryMethod != null) {
1023 					resolved = true;
1024 					autowireNecessary = mbd.constructorArgumentsResolved;
1025 				}
1026 			}
1027 		}
1028 		if (resolved) {
1029 			if (autowireNecessary) {
1030 				return autowireConstructor(beanName, mbd, null, null);
1031 			}
1032 			else {
1033 				return instantiateBean(beanName, mbd);
1034 			}
1035 		}
1036 
1037 		// Need to determine the constructor...
1038 		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
1039 		if (ctors != null ||
1040 				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
1041 				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
1042 			return autowireConstructor(beanName, mbd, ctors, args);
1043 		}
1044 
1045 		// No special handling: simply use no-arg constructor.
1046 		return instantiateBean(beanName, mbd);
1047 	}
1048 
1049 	/**
1050 	 * Determine candidate constructors to use for the given bean, checking all registered
1051 	 * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
1052 	 * @param beanClass the raw class of the bean
1053 	 * @param beanName the name of the bean
1054 	 * @return the candidate constructors, or {@code null} if none specified
1055 	 * @throws org.springframework.beans.BeansException in case of errors
1056 	 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
1057 	 */
1058 	protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
1059 			throws BeansException {
1060 
1061 		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
1062 			for (BeanPostProcessor bp : getBeanPostProcessors()) {
1063 				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
1064 					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
1065 					Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
1066 					if (ctors != null) {
1067 						return ctors;
1068 					}
1069 				}
1070 			}
1071 		}
1072 		return null;
1073 	}
1074 
1075 	/**
1076 	 * Instantiate the given bean using its default constructor.
1077 	 * @param beanName the name of the bean
1078 	 * @param mbd the bean definition for the bean
1079 	 * @return BeanWrapper for the new instance
1080 	 */
1081 	protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
1082 		try {
1083 			Object beanInstance;
1084 			final BeanFactory parent = this;
1085 			if (System.getSecurityManager() != null) {
1086 				beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
1087 					@Override
1088 					public Object run() {
1089 						return getInstantiationStrategy().instantiate(mbd, beanName, parent);
1090 					}
1091 				}, getAccessControlContext());
1092 			}
1093 			else {
1094 				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
1095 			}
1096 			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
1097 			initBeanWrapper(bw);
1098 			return bw;
1099 		}
1100 		catch (Throwable ex) {
1101 			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
1102 		}
1103 	}
1104 
1105 	/**
1106 	 * Instantiate the bean using a named factory method. The method may be static, if the
1107 	 * mbd parameter specifies a class, rather than a factoryBean, or an instance variable
1108 	 * on a factory object itself configured using Dependency Injection.
1109 	 * @param beanName the name of the bean
1110 	 * @param mbd the bean definition for the bean
1111 	 * @param explicitArgs argument values passed in programmatically via the getBean method,
1112 	 * or {@code null} if none (-> use constructor argument values from bean definition)
1113 	 * @return BeanWrapper for the new instance
1114 	 * @see #getBean(String, Object[])
1115 	 */
1116 	protected BeanWrapper instantiateUsingFactoryMethod(
1117 			String beanName, RootBeanDefinition mbd, Object[] explicitArgs) {
1118 
1119 		return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
1120 	}
1121 
1122 	/**
1123 	 * "autowire constructor" (with constructor arguments by type) behavior.
1124 	 * Also applied if explicit constructor argument values are specified,
1125 	 * matching all remaining arguments with beans from the bean factory.
1126 	 * <p>This corresponds to constructor injection: In this mode, a Spring
1127 	 * bean factory is able to host components that expect constructor-based
1128 	 * dependency resolution.
1129 	 * @param beanName the name of the bean
1130 	 * @param mbd the bean definition for the bean
1131 	 * @param ctors the chosen candidate constructors
1132 	 * @param explicitArgs argument values passed in programmatically via the getBean method,
1133 	 * or {@code null} if none (-> use constructor argument values from bean definition)
1134 	 * @return BeanWrapper for the new instance
1135 	 */
1136 	protected BeanWrapper autowireConstructor(
1137 			String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) {
1138 
1139 		return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
1140 	}
1141 
1142 	/**
1143 	 * Populate the bean instance in the given BeanWrapper with the property values
1144 	 * from the bean definition.
1145 	 * @param beanName the name of the bean
1146 	 * @param mbd the bean definition for the bean
1147 	 * @param bw BeanWrapper with bean instance
1148 	 */
1149 	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
1150 		PropertyValues pvs = mbd.getPropertyValues();
1151 
1152 		if (bw == null) {
1153 			if (!pvs.isEmpty()) {
1154 				throw new BeanCreationException(
1155 						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
1156 			}
1157 			else {
1158 				// Skip property population phase for null instance.
1159 				return;
1160 			}
1161 		}
1162 
1163 		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
1164 		// state of the bean before properties are set. This can be used, for example,
1165 		// to support styles of field injection.
1166 		boolean continueWithPropertyPopulation = true;
1167 
1168 		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
1169 			for (BeanPostProcessor bp : getBeanPostProcessors()) {
1170 				if (bp instanceof InstantiationAwareBeanPostProcessor) {
1171 					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
1172 					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
1173 						continueWithPropertyPopulation = false;
1174 						break;
1175 					}
1176 				}
1177 			}
1178 		}
1179 
1180 		if (!continueWithPropertyPopulation) {
1181 			return;
1182 		}
1183 
1184 		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
1185 				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
1186 			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
1187 
1188 			// Add property values based on autowire by name if applicable.
1189 			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
1190 				autowireByName(beanName, mbd, bw, newPvs);
1191 			}
1192 
1193 			// Add property values based on autowire by type if applicable.
1194 			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
1195 				autowireByType(beanName, mbd, bw, newPvs);
1196 			}
1197 
1198 			pvs = newPvs;
1199 		}
1200 
1201 		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
1202 		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
1203 
1204 		if (hasInstAwareBpps || needsDepCheck) {
1205 			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
1206 			if (hasInstAwareBpps) {
1207 				for (BeanPostProcessor bp : getBeanPostProcessors()) {
1208 					if (bp instanceof InstantiationAwareBeanPostProcessor) {
1209 						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
1210 						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
1211 						if (pvs == null) {
1212 							return;
1213 						}
1214 					}
1215 				}
1216 			}
1217 			if (needsDepCheck) {
1218 				checkDependencies(beanName, mbd, filteredPds, pvs);
1219 			}
1220 		}
1221 
1222 		applyPropertyValues(beanName, mbd, bw, pvs);
1223 	}
1224 
1225 	/**
1226 	 * Fill in any missing property values with references to
1227 	 * other beans in this factory if autowire is set to "byName".
1228 	 * @param beanName the name of the bean we're wiring up.
1229 	 * Useful for debugging messages; not used functionally.
1230 	 * @param mbd bean definition to update through autowiring
1231 	 * @param bw BeanWrapper from which we can obtain information about the bean
1232 	 * @param pvs the PropertyValues to register wired objects with
1233 	 */
1234 	protected void autowireByName(
1235 			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
1236 
1237 		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
1238 		for (String propertyName : propertyNames) {
1239 			if (containsBean(propertyName)) {
1240 				Object bean = getBean(propertyName);
1241 				pvs.add(propertyName, bean);
1242 				registerDependentBean(propertyName, beanName);
1243 				if (logger.isDebugEnabled()) {
1244 					logger.debug("Added autowiring by name from bean name '" + beanName +
1245 							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
1246 				}
1247 			}
1248 			else {
1249 				if (logger.isTraceEnabled()) {
1250 					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
1251 							"' by name: no matching bean found");
1252 				}
1253 			}
1254 		}
1255 	}
1256 
1257 	/**
1258 	 * Abstract method defining "autowire by type" (bean properties by type) behavior.
1259 	 * <p>This is like PicoContainer default, in which there must be exactly one bean
1260 	 * of the property type in the bean factory. This makes bean factories simple to
1261 	 * configure for small namespaces, but doesn't work as well as standard Spring
1262 	 * behavior for bigger applications.
1263 	 * @param beanName the name of the bean to autowire by type
1264 	 * @param mbd the merged bean definition to update through autowiring
1265 	 * @param bw BeanWrapper from which we can obtain information about the bean
1266 	 * @param pvs the PropertyValues to register wired objects with
1267 	 */
1268 	protected void autowireByType(
1269 			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
1270 
1271 		TypeConverter converter = getCustomTypeConverter();
1272 		if (converter == null) {
1273 			converter = bw;
1274 		}
1275 
1276 		Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
1277 		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
1278 		for (String propertyName : propertyNames) {
1279 			try {
1280 				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
1281 				// Don't try autowiring by type for type Object: never makes sense,
1282 				// even if it technically is a unsatisfied, non-simple property.
1283 				if (!Object.class.equals(pd.getPropertyType())) {
1284 					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
1285 					// Do not allow eager init for type matching in case of a prioritized post-processor.
1286 					boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
1287 					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
1288 					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
1289 					if (autowiredArgument != null) {
1290 						pvs.add(propertyName, autowiredArgument);
1291 					}
1292 					for (String autowiredBeanName : autowiredBeanNames) {
1293 						registerDependentBean(autowiredBeanName, beanName);
1294 						if (logger.isDebugEnabled()) {
1295 							logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
1296 									propertyName + "' to bean named '" + autowiredBeanName + "'");
1297 						}
1298 					}
1299 					autowiredBeanNames.clear();
1300 				}
1301 			}
1302 			catch (BeansException ex) {
1303 				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
1304 			}
1305 		}
1306 	}
1307 
1308 
1309 	/**
1310 	 * Return an array of non-simple bean properties that are unsatisfied.
1311 	 * These are probably unsatisfied references to other beans in the
1312 	 * factory. Does not include simple properties like primitives or Strings.
1313 	 * @param mbd the merged bean definition the bean was created with
1314 	 * @param bw the BeanWrapper the bean was created with
1315 	 * @return an array of bean property names
1316 	 * @see org.springframework.beans.BeanUtils#isSimpleProperty
1317 	 */
1318 	protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
1319 		Set<String> result = new TreeSet<String>();
1320 		PropertyValues pvs = mbd.getPropertyValues();
1321 		PropertyDescriptor[] pds = bw.getPropertyDescriptors();
1322 		for (PropertyDescriptor pd : pds) {
1323 			if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
1324 					!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
1325 				result.add(pd.getName());
1326 			}
1327 		}
1328 		return StringUtils.toStringArray(result);
1329 	}
1330 
1331 	/**
1332 	 * Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
1333 	 * excluding ignored dependency types or properties defined on ignored dependency interfaces.
1334 	 * @param bw the BeanWrapper the bean was created with
1335 	 * @param cache whether to cache filtered PropertyDescriptors for the given bean Class
1336 	 * @return the filtered PropertyDescriptors
1337 	 * @see #isExcludedFromDependencyCheck
1338 	 * @see #filterPropertyDescriptorsForDependencyCheck(org.springframework.beans.BeanWrapper)
1339 	 */
1340 	protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
1341 		PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
1342 		if (filtered == null) {
1343 			filtered = filterPropertyDescriptorsForDependencyCheck(bw);
1344 			if (cache) {
1345 				PropertyDescriptor[] existing =
1346 						this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered);
1347 				if (existing != null) {
1348 					filtered = existing;
1349 				}
1350 			}
1351 		}
1352 		return filtered;
1353 	}
1354 
1355 	/**
1356 	 * Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
1357 	 * excluding ignored dependency types or properties defined on ignored dependency interfaces.
1358 	 * @param bw the BeanWrapper the bean was created with
1359 	 * @return the filtered PropertyDescriptors
1360 	 * @see #isExcludedFromDependencyCheck
1361 	 */
1362 	protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
1363 		List<PropertyDescriptor> pds =
1364 				new LinkedList<PropertyDescriptor>(Arrays.asList(bw.getPropertyDescriptors()));
1365 		for (Iterator<PropertyDescriptor> it = pds.iterator(); it.hasNext();) {
1366 			PropertyDescriptor pd = it.next();
1367 			if (isExcludedFromDependencyCheck(pd)) {
1368 				it.remove();
1369 			}
1370 		}
1371 		return pds.toArray(new PropertyDescriptor[pds.size()]);
1372 	}
1373 
1374 	/**
1375 	 * Determine whether the given bean property is excluded from dependency checks.
1376 	 * <p>This implementation excludes properties defined by CGLIB and
1377 	 * properties whose type matches an ignored dependency type or which
1378 	 * are defined by an ignored dependency interface.
1379 	 * @param pd the PropertyDescriptor of the bean property
1380 	 * @return whether the bean property is excluded
1381 	 * @see #ignoreDependencyType(Class)
1382 	 * @see #ignoreDependencyInterface(Class)
1383 	 */
1384 	protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
1385 		return (AutowireUtils.isExcludedFromDependencyCheck(pd) ||
1386 				this.ignoredDependencyTypes.contains(pd.getPropertyType()) ||
1387 				AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces));
1388 	}
1389 
1390 	/**
1391 	 * Perform a dependency check that all properties exposed have been set,
1392 	 * if desired. Dependency checks can be objects (collaborating beans),
1393 	 * simple (primitives and String), or all (both).
1394 	 * @param beanName the name of the bean
1395 	 * @param mbd the merged bean definition the bean was created with
1396 	 * @param pds the relevant property descriptors for the target bean
1397 	 * @param pvs the property values to be applied to the bean
1398 	 * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
1399 	 */
1400 	protected void checkDependencies(
1401 			String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, PropertyValues pvs)
1402 			throws UnsatisfiedDependencyException {
1403 
1404 		int dependencyCheck = mbd.getDependencyCheck();
1405 		for (PropertyDescriptor pd : pds) {
1406 			if (pd.getWriteMethod() != null && !pvs.contains(pd.getName())) {
1407 				boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
1408 				boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) ||
1409 						(isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
1410 						(!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
1411 				if (unsatisfied) {
1412 					throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
1413 							"Set this property value or disable dependency checking for this bean.");
1414 				}
1415 			}
1416 		}
1417 	}
1418 
1419 	/**
1420 	 * Apply the given property values, resolving any runtime references
1421 	 * to other beans in this bean factory. Must use deep copy, so we
1422 	 * don't permanently modify this property.
1423 	 * @param beanName the bean name passed for better exception information
1424 	 * @param mbd the merged bean definition
1425 	 * @param bw the BeanWrapper wrapping the target object
1426 	 * @param pvs the new property values
1427 	 */
1428 	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
1429 		if (pvs == null || pvs.isEmpty()) {
1430 			return;
1431 		}
1432 
1433 		MutablePropertyValues mpvs = null;
1434 		List<PropertyValue> original;
1435 
1436 		if (System.getSecurityManager() != null) {
1437 			if (bw instanceof BeanWrapperImpl) {
1438 				((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
1439 			}
1440 		}
1441 
1442 		if (pvs instanceof MutablePropertyValues) {
1443 			mpvs = (MutablePropertyValues) pvs;
1444 			if (mpvs.isConverted()) {
1445 				// Shortcut: use the pre-converted values as-is.
1446 				try {
1447 					bw.setPropertyValues(mpvs);
1448 					return;
1449 				}
1450 				catch (BeansException ex) {
1451 					throw new BeanCreationException(
1452 							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
1453 				}
1454 			}
1455 			original = mpvs.getPropertyValueList();
1456 		}
1457 		else {
1458 			original = Arrays.asList(pvs.getPropertyValues());
1459 		}
1460 
1461 		TypeConverter converter = getCustomTypeConverter();
1462 		if (converter == null) {
1463 			converter = bw;
1464 		}
1465 		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
1466 
1467 		// Create a deep copy, resolving any references for values.
1468 		List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
1469 		boolean resolveNecessary = false;
1470 		for (PropertyValue pv : original) {
1471 			if (pv.isConverted()) {
1472 				deepCopy.add(pv);
1473 			}
1474 			else {
1475 				String propertyName = pv.getName();
1476 				Object originalValue = pv.getValue();
1477 				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
1478 				Object convertedValue = resolvedValue;
1479 				boolean convertible = bw.isWritableProperty(propertyName) &&
1480 						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
1481 				if (convertible) {
1482 					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
1483 				}
1484 				// Possibly store converted value in merged bean definition,
1485 				// in order to avoid re-conversion for every created bean instance.
1486 				if (resolvedValue == originalValue) {
1487 					if (convertible) {
1488 						pv.setConvertedValue(convertedValue);
1489 					}
1490 					deepCopy.add(pv);
1491 				}
1492 				else if (convertible && originalValue instanceof TypedStringValue &&
1493 						!((TypedStringValue) originalValue).isDynamic() &&
1494 						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
1495 					pv.setConvertedValue(convertedValue);
1496 					deepCopy.add(pv);
1497 				}
1498 				else {
1499 					resolveNecessary = true;
1500 					deepCopy.add(new PropertyValue(pv, convertedValue));
1501 				}
1502 			}
1503 		}
1504 		if (mpvs != null && !resolveNecessary) {
1505 			mpvs.setConverted();
1506 		}
1507 
1508 		// Set our (possibly massaged) deep copy.
1509 		try {
1510 			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
1511 		}
1512 		catch (BeansException ex) {
1513 			throw new BeanCreationException(
1514 					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
1515 		}
1516 	}
1517 
1518 	/**
1519 	 * Convert the given value for the specified target property.
1520 	 */
1521 	private Object convertForProperty(Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
1522 		if (converter instanceof BeanWrapperImpl) {
1523 			return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
1524 		}
1525 		else {
1526 			PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
1527 			MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
1528 			return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
1529 		}
1530 	}
1531 
1532 
1533 	/**
1534 	 * Initialize the given bean instance, applying factory callbacks
1535 	 * as well as init methods and bean post processors.
1536 	 * <p>Called from {@link #createBean} for traditionally defined beans,
1537 	 * and from {@link #initializeBean} for existing bean instances.
1538 	 * @param beanName the bean name in the factory (for debugging purposes)
1539 	 * @param bean the new bean instance we may need to initialize
1540 	 * @param mbd the bean definition that the bean was created with
1541 	 * (can also be {@code null}, if given an existing bean instance)
1542 	 * @return the initialized bean instance (potentially wrapped)
1543 	 * @see BeanNameAware
1544 	 * @see BeanClassLoaderAware
1545 	 * @see BeanFactoryAware
1546 	 * @see #applyBeanPostProcessorsBeforeInitialization
1547 	 * @see #invokeInitMethods
1548 	 * @see #applyBeanPostProcessorsAfterInitialization
1549 	 */
1550 	protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
1551 		if (System.getSecurityManager() != null) {
1552 			AccessController.doPrivileged(new PrivilegedAction<Object>() {
1553 				@Override
1554 				public Object run() {
1555 					invokeAwareMethods(beanName, bean);
1556 					return null;
1557 				}
1558 			}, getAccessControlContext());
1559 		}
1560 		else {
1561 			invokeAwareMethods(beanName, bean);
1562 		}
1563 
1564 		Object wrappedBean = bean;
1565 		if (mbd == null || !mbd.isSynthetic()) {
1566 			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
1567 		}
1568 
1569 		try {
1570 			invokeInitMethods(beanName, wrappedBean, mbd);
1571 		}
1572 		catch (Throwable ex) {
1573 			throw new BeanCreationException(
1574 					(mbd != null ? mbd.getResourceDescription() : null),
1575 					beanName, "Invocation of init method failed", ex);
1576 		}
1577 
1578 		if (mbd == null || !mbd.isSynthetic()) {
1579 			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
1580 		}
1581 		return wrappedBean;
1582 	}
1583 
1584 	private void invokeAwareMethods(final String beanName, final Object bean) {
1585 		if (bean instanceof Aware) {
1586 			if (bean instanceof BeanNameAware) {
1587 				((BeanNameAware) bean).setBeanName(beanName);
1588 			}
1589 			if (bean instanceof BeanClassLoaderAware) {
1590 				((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
1591 			}
1592 			if (bean instanceof BeanFactoryAware) {
1593 				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
1594 			}
1595 		}
1596 	}
1597 
1598 	/**
1599 	 * Give a bean a chance to react now all its properties are set,
1600 	 * and a chance to know about its owning bean factory (this object).
1601 	 * This means checking whether the bean implements InitializingBean or defines
1602 	 * a custom init method, and invoking the necessary callback(s) if it does.
1603 	 * @param beanName the bean name in the factory (for debugging purposes)
1604 	 * @param bean the new bean instance we may need to initialize
1605 	 * @param mbd the merged bean definition that the bean was created with
1606 	 * (can also be {@code null}, if given an existing bean instance)
1607 	 * @throws Throwable if thrown by init methods or by the invocation process
1608 	 * @see #invokeCustomInitMethod
1609 	 */
1610 	protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
1611 			throws Throwable {
1612 
1613 		boolean isInitializingBean = (bean instanceof InitializingBean);
1614 		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
1615 			if (logger.isDebugEnabled()) {
1616 				logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
1617 			}
1618 			if (System.getSecurityManager() != null) {
1619 				try {
1620 					AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
1621 						@Override
1622 						public Object run() throws Exception {
1623 							((InitializingBean) bean).afterPropertiesSet();
1624 							return null;
1625 						}
1626 					}, getAccessControlContext());
1627 				}
1628 				catch (PrivilegedActionException pae) {
1629 					throw pae.getException();
1630 				}
1631 			}
1632 			else {
1633 				((InitializingBean) bean).afterPropertiesSet();
1634 			}
1635 		}
1636 
1637 		if (mbd != null) {
1638 			String initMethodName = mbd.getInitMethodName();
1639 			if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
1640 					!mbd.isExternallyManagedInitMethod(initMethodName)) {
1641 				invokeCustomInitMethod(beanName, bean, mbd);
1642 			}
1643 		}
1644 	}
1645 
1646 	/**
1647 	 * Invoke the specified custom init method on the given bean.
1648 	 * Called by invokeInitMethods.
1649 	 * <p>Can be overridden in subclasses for custom resolution of init
1650 	 * methods with arguments.
1651 	 * @see #invokeInitMethods
1652 	 */
1653 	protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
1654 		String initMethodName = mbd.getInitMethodName();
1655 		final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
1656 				BeanUtils.findMethod(bean.getClass(), initMethodName) :
1657 				ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
1658 		if (initMethod == null) {
1659 			if (mbd.isEnforceInitMethod()) {
1660 				throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
1661 						initMethodName + "' on bean with name '" + beanName + "'");
1662 			}
1663 			else {
1664 				if (logger.isDebugEnabled()) {
1665 					logger.debug("No default init method named '" + initMethodName +
1666 							"' found on bean with name '" + beanName + "'");
1667 				}
1668 				// Ignore non-existent default lifecycle methods.
1669 				return;
1670 			}
1671 		}
1672 
1673 		if (logger.isDebugEnabled()) {
1674 			logger.debug("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
1675 		}
1676 
1677 		if (System.getSecurityManager() != null) {
1678 			AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
1679 				@Override
1680 				public Object run() throws Exception {
1681 					ReflectionUtils.makeAccessible(initMethod);
1682 					return null;
1683 				}
1684 			});
1685 			try {
1686 				AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
1687 					@Override
1688 					public Object run() throws Exception {
1689 						initMethod.invoke(bean);
1690 						return null;
1691 					}
1692 				}, getAccessControlContext());
1693 			}
1694 			catch (PrivilegedActionException pae) {
1695 				InvocationTargetException ex = (InvocationTargetException) pae.getException();
1696 				throw ex.getTargetException();
1697 			}
1698 		}
1699 		else {
1700 			try {
1701 				ReflectionUtils.makeAccessible(initMethod);
1702 				initMethod.invoke(bean);
1703 			}
1704 			catch (InvocationTargetException ex) {
1705 				throw ex.getTargetException();
1706 			}
1707 		}
1708 	}
1709 
1710 
1711 	/**
1712 	 * Applies the {@code postProcessAfterInitialization} callback of all
1713 	 * registered BeanPostProcessors, giving them a chance to post-process the
1714 	 * object obtained from FactoryBeans (for example, to auto-proxy them).
1715 	 * @see #applyBeanPostProcessorsAfterInitialization
1716 	 */
1717 	@Override
1718 	protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
1719 		return applyBeanPostProcessorsAfterInitialization(object, beanName);
1720 	}
1721 
1722 	/**
1723 	 * Overridden to clear FactoryBean instance cache as well.
1724 	 */
1725 	@Override
1726 	protected void removeSingleton(String beanName) {
1727 		super.removeSingleton(beanName);
1728 		this.factoryBeanInstanceCache.remove(beanName);
1729 	}
1730 
1731 
1732 	/**
1733 	 * Special DependencyDescriptor variant for Spring's good old autowire="byType" mode.
1734 	 * Always optional; never considering the parameter name for choosing a primary candidate.
1735 	 */
1736 	@SuppressWarnings("serial")
1737 	private static class AutowireByTypeDependencyDescriptor extends DependencyDescriptor {
1738 
1739 		public AutowireByTypeDependencyDescriptor(MethodParameter methodParameter, boolean eager) {
1740 			super(methodParameter, false, eager);
1741 		}
1742 
1743 		@Override
1744 		public String getDependencyName() {
1745 			return null;
1746 		}
1747 	}
1748 
1749 }