1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
118 implements AutowireCapableBeanFactory {
119
120
121 private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
122
123
124 private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
125
126
127 private boolean allowCircularReferences = true;
128
129
130
131
132
133 private boolean allowRawInjectionDespiteWrapping = false;
134
135
136
137
138
139 private final Set<Class<?>> ignoredDependencyTypes = new HashSet<Class<?>>();
140
141
142
143
144
145 private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<Class<?>>();
146
147
148 private final Map<String, BeanWrapper> factoryBeanInstanceCache =
149 new ConcurrentHashMap<String, BeanWrapper>(16);
150
151
152 private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
153 new ConcurrentHashMap<Class<?>, PropertyDescriptor[]>(64);
154
155
156
157
158
159 public AbstractAutowireCapableBeanFactory() {
160 super();
161 ignoreDependencyInterface(BeanNameAware.class);
162 ignoreDependencyInterface(BeanFactoryAware.class);
163 ignoreDependencyInterface(BeanClassLoaderAware.class);
164 }
165
166
167
168
169
170 public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
171 this();
172 setParentBeanFactory(parentBeanFactory);
173 }
174
175
176
177
178
179
180
181 public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
182 this.instantiationStrategy = instantiationStrategy;
183 }
184
185
186
187
188 protected InstantiationStrategy getInstantiationStrategy() {
189 return this.instantiationStrategy;
190 }
191
192
193
194
195
196
197 public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
198 this.parameterNameDiscoverer = parameterNameDiscoverer;
199 }
200
201
202
203
204
205 protected ParameterNameDiscoverer getParameterNameDiscoverer() {
206 return this.parameterNameDiscoverer;
207 }
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 public void setAllowCircularReferences(boolean allowCircularReferences) {
223 this.allowCircularReferences = allowCircularReferences;
224 }
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240 public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
241 this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
242 }
243
244
245
246
247
248 public void ignoreDependencyType(Class<?> type) {
249 this.ignoredDependencyTypes.add(type);
250 }
251
252
253
254
255
256
257
258
259
260
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
282
283
284 @Override
285 @SuppressWarnings("unchecked")
286 public <T> T createBean(Class<T> beanClass) throws BeansException {
287
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
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
335
336
337 @Override
338 public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
339
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
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
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
438
439
440
441
442
443
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
453 resolveBeanClass(mbd, beanName);
454
455
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
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
485
486
487
488
489
490
491
492
493
494
495
496
497 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
498
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
510 synchronized (mbd.postProcessingLock) {
511 if (!mbd.postProcessed) {
512 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
513 mbd.postProcessed = true;
514 }
515 }
516
517
518
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
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
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
594
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
612
613
614
615
616
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
632
633
634
635
636
637
638
639
640
641
642
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
660 factoryClass = getType(factoryBeanName);
661 isStatic = false;
662 }
663 else {
664
665 factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
666 }
667
668 if (factoryClass == null) {
669 return null;
670 }
671
672
673
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
683 if (factoryMethod.getTypeParameters().length > 0) {
684 try {
685
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
728 if (cache) {
729 mbd.resolvedFactoryMethodReturnType = commonType;
730 }
731 return commonType;
732 }
733 else {
734
735 return null;
736 }
737 }
738
739
740
741
742
743
744
745
746
747
748
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
760 BeanDefinition fbDef = getBeanDefinition(factoryBeanName);
761 if (fbDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) fbDef).hasBeanClass()) {
762
763 Class<?> fbClass = ClassUtils.getUserClass(((AbstractBeanDefinition) fbDef).getBeanClass());
764
765
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
782
783
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
795 objectType.value = getTypeForFactoryBean(fb);
796 if (objectType.value != null) {
797 return objectType.value;
798 }
799 }
800
801
802 return super.getTypeForFactoryBean(beanName, mbd);
803 }
804
805
806
807
808
809
810
811
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
832
833
834
835
836
837
838
839
840
841
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
856 beforeSingletonCreation(beanName);
857
858 instance = resolveBeforeInstantiation(beanName, mbd);
859 if (instance == null) {
860 bw = createBeanInstance(beanName, mbd, null);
861 instance = bw.getWrappedInstance();
862 }
863 }
864 finally {
865
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
878
879
880
881
882
883
884
885 private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
886 if (isPrototypeCurrentlyInCreation(beanName)) {
887 return null;
888 }
889 Object instance = null;
890 try {
891
892 beforePrototypeCreation(beanName);
893
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
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
910 afterPrototypeCreation(beanName);
911 }
912 return getFactoryBean(beanName, instance);
913 }
914
915
916
917
918
919
920
921
922
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
943
944
945
946
947
948 protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
949 Object bean = null;
950 if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
951
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
968
969
970
971
972
973
974
975
976
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
995
996
997
998
999
1000
1001
1002
1003
1004 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
1005
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
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
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
1046 return instantiateBean(beanName, mbd);
1047 }
1048
1049
1050
1051
1052
1053
1054
1055
1056
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
1077
1078
1079
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
1107
1108
1109
1110
1111
1112
1113
1114
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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
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
1144
1145
1146
1147
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
1159 return;
1160 }
1161 }
1162
1163
1164
1165
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
1189 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
1190 autowireByName(beanName, mbd, bw, newPvs);
1191 }
1192
1193
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
1227
1228
1229
1230
1231
1232
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
1259
1260
1261
1262
1263
1264
1265
1266
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
1282
1283 if (!Object.class.equals(pd.getPropertyType())) {
1284 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
1285
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
1311
1312
1313
1314
1315
1316
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
1333
1334
1335
1336
1337
1338
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
1357
1358
1359
1360
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
1376
1377
1378
1379
1380
1381
1382
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
1392
1393
1394
1395
1396
1397
1398
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
1421
1422
1423
1424
1425
1426
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
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
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
1485
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
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
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
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
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
1600
1601
1602
1603
1604
1605
1606
1607
1608
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
1648
1649
1650
1651
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
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
1713
1714
1715
1716
1717 @Override
1718 protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
1719 return applyBeanPostProcessorsAfterInitialization(object, beanName);
1720 }
1721
1722
1723
1724
1725 @Override
1726 protected void removeSingleton(String beanName) {
1727 super.removeSingleton(beanName);
1728 this.factoryBeanInstanceCache.remove(beanName);
1729 }
1730
1731
1732
1733
1734
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 }