docs/Spring全家桶/Spring源码分析/Spring启动流程/Spring启动流程(九):单例bean的创建.md
ģǷ finishBeanFactoryInitialization(beanFactory)Ľص bean Ĵ̡
һƪУǽ AbstractApplicationContext#finishBeanFactoryInitialization ִй̣Ľϸڣ spring bean Ĵ̡
|-AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
|-AbstractApplicationContext#refresh
|-AbstractApplicationContext#finishBeanFactoryInitialization
|-DefaultListableBeanFactory#preInstantiateSingletons
|-AbstractBeanFactory#getBean(java.lang.String)
|-AbstractBeanFactory#doGetBean
|-AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])
ֱӿ AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])Ĵ£
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
// ȷ BeanDefinition е Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// дbeanж <lookup-method /> <replaced-method />
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
...
}
try {
// дĻֱӷ
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
...
}
try {
// bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
...
}
catch (Throwable ex) {
...
}
}
Կ÷ļ£
ǰIJעǽĸ AbstractAutowireCapableBeanFactory#doCreateBean:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd,
final @Nullable Object[] args) throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// factoryBeanӻɾ
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// ʵ Beanյ
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//beanʵ
final Object bean = instanceWrapper.getWrappedInstance();
//bean
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// ѭMergedBeanDefinitionPostProcessorpostProcessMergedBeanDefinition磬
// 1\. AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ϊҵ
// @Autowired@Value עԺͷ
// 2\. CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ϊҵ
// @Resource עԺͷ
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
...
}
mbd.postProcessed = true;
}
}
// ѭ, Ƿѭ, allowCircularReferencesĬΪtrueԹر
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// ѭĽᵥ
...
}
Object exposedObject = bean;
try {
// װ, Ҳdz˵Զע룬Ҫ
populateBean(beanName, mbd, instanceWrapper);
// Ǵbeanʼɺĸֻص
// init-methodInitializingBean ӿڡBeanPostProcessor ӿ
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
...
}
//ͬģѭ
if (earlySingletonExposure) {
// ѭĽᵥ
...
}
// beanעᵽӦScope
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
...
}
return exposedObject;
}
Կspring ڴ bean ʱҪ£
ǾҪĸ衣
spring ʵķ AbstractAutowireCapableBeanFactory#createBeanInstance£
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd,
@Nullable Object[] args) {
// ȷѾ˴ class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// УķȨ
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers())
&& !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(...);
}
// ǷbeanSupplierSupplierjava8ṩ࣬Դһlambdaʽ
// AbstractBeanDefinition#setInstanceSupplier ָ
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
// ùʵ
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Ƿһ
boolean resolved = false;
// Ƿù캯ע
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
// ι캯
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// жǷвι캯
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
// 캯ע
return autowireConstructor(beanName, mbd, ctors, null);
}
// ι캯
return instantiateBean(beanName, mbd);
}
ϴspring ʵ bean ʱ 4 ַʽ
ǰǿָķûɶ˵ģ spring ʵѡ췽ʵġһ bean ˵δṩκι췽ṩι췽 AbstractAutowireCapableBeanFactory#instantiateBean ʵ AbstractAutowireCapableBeanFactory#autowireConstructor ʵʵϣնִе BeanUtils#instantiateClass(Constructor<T>, Object...):
public static <T> T instantiateClass(Constructor<T> ctor, Object... args)
throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
if (KotlinDetector.isKotlinReflectPresent()
&& KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
return KotlinDelegate.instantiateClass(ctor, args);
}
else {
Class<?>[] parameterTypes = ctor.getParameterTypes();
Assert.isTrue(args.length <= parameterTypes.length, "...");
Object[] argsWithDefaultValues = new Object[args.length];
for (int i = 0 ; i < args.length; i++) {
if (args[i] == null) {
Class<?> parameterType = parameterTypes[i];
argsWithDefaultValues[i] = (parameterType.isPrimitive()
? DEFAULT_TYPE_VALUES.get(parameterType) : null);
}
else {
argsWithDefaultValues[i] = args[i];
}
}
// ʵ
return ctor.newInstance(argsWithDefaultValues);
}
}
catch (...) {
...
}
}
Կյõ java.lang.reflect.Constructor#newInstance jdk ķˡ
⣬ bean ṩ˶ 췽ʱspring һӵƶϻƣƶϳѵĹ췽Ͳչˡ
ǽעˣעǰҪ֪ЩҪע롣spring Բ AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors еúôвģ
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd,
Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
// úô
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
ЩôУ
AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ҵ @Autowired``@Value עԺͷCommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ҵ @Resource עԺͷΪ˷˵ @Autowired ע̣ demo01 org.springframework.learn.demo01.BeanObj1 д룺
package org.springframework.learn.demo01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BeanObj1 {
// Ϊ¼Ĵ
@Autowired
private BeanObj2 beanObj2;
public BeanObj1() {
System.out.println("beanObj1Ĺ췽");
}
@Override
public String toString() {
return "BeanObj1{}";
}
}
AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition,
Class<?> beanType, String beanName) {
// 뷽
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
// ֤ҵ뷽עᵽbeanDefinition
metadata.checkConfigMembers(beanDefinition);
}
һ· AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata:
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
...
// һѭ굱ǰҵǰĸֱ࣬Object
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
//
ReflectionUtils.doWithLocalFields(targetClass, field -> {
MergedAnnotation<?> ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
return;
}
boolean required = determineRequiredStatus(ann);
// Էװ AutowiredFieldElement
currElements.add(new AutowiredFieldElement(field, required));
}
});
// ҷ
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
return;
}
if (method.getParameterCount() == 0) {
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
// װ AutowiredMethodElement
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return InjectionMetadata.forElements(elements, clazz);
}
ϴDzҹ̣ܽ£
AutowiredFieldElementҵװΪ AutowiredMethodElementfindAutowiredAnnotationǾͿ findAutowiredAnnotation νвҵġ AutowiredAnnotationBeanPostProcessor#findAutowiredAnnotation £
private final Set<Class<? extends Annotation>> autowiredAnnotationTypes
= new LinkedHashSet<>(4);
// ĬϹ췽ָ@Autowired@Valueע
@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
...
}
// Dzҷ
@Nullable
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
MergedAnnotations annotations = MergedAnnotations.from(ao);
// autowiredAnnotationTypes @Autowired@Valueע
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
MergedAnnotation<?> annotation = annotations.get(type);
if (annotation.isPresent()) {
return annotation;
}
}
return null;
}
ϴעúˣͲ˵ˡ
ҵ뷽žעᵽ beanDefinition ˣ InjectionMetadata#checkConfigMembers Ĺ
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
// עᵽ beanDefinition
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
}
}
this.checkedElements = checkedElements;
}
νעᣬʵҲ൱ beanDefinition е externallyManagedConfigMembers һ¼
RootBeanDefinition#registerExternallyManagedConfigMember
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedConfigMembers == null) {
this.externallyManagedConfigMembers = new HashSet<>(1);
}
// setһ¼
this.externallyManagedConfigMembers.add(configMember);
}
}
spring עڷ AbstractAutowireCapableBeanFactory#populateBean дģ£
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(...);
}
else {
return;
}
}
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// þĺô
// AutowiredAnnotationBeanPostProcessor.postProcessProperties @Autowired@Value ע
// CommonAnnotationBeanPostProcessor.postProcessProperties @Resourceע
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// falseҪкֵҲҪپ BeanPostProcessor Ĵ
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
// bean
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// עΪbyTypebyNameע@Autowired ȲbyTypeҲbyName,ﷵfalse
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// ͨҵֵ bean ȳʼ bean¼ϵ
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// ͨװ䡣һЩ
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// úôע͵
// @Autowiredע AutowiredAnnotationBeanPostProcessor
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// Ϸᵽö@AutowiredһBeanPostProcessor
// б@Autowired@Value עԽֵ
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds,
bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
// bean ʵֵ
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
spring ںôнеģ@Autowired ䷽Ϊ AutowiredAnnotationBeanPostProcessor#postProcessProperties:
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// findAutowiringMetadata ȷע @Autowired @Value ע뷽ȡɹ
// findAutowiringMetadata Է֣һ棬ֻеһβŻȥȡ֮ӻлȡ
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// ע
metadata.inject(bean, beanName, pvs);
}
catch (...) {
...
}
}
ٽ InjectionMetadata#inject
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs)
throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
// InjectedElement AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata
// вҵģfield װΪ AutowiredFieldElementmethod װΪ AutowiredMethodElement
for (InjectedElement element : elementsToIterate) {
element.inject(target, beanName, pvs);
}
}
}
ٸ element.inject(target, beanName, pvs)õ AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
@Override
protected void inject(Object bean, @Nullable String beanName,
@Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// һоǻȡעbean
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
...
}
...
}
// ֵͨ
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
ϴеֻ࣬ҪҪעдˣ
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter)ReflectionUtils.makeAccessible(field);field.set(bean, value);ڵ 2 㣬յõ jdk ṩķ䷽ûʲô˵ġص spring λȡҪע bean
beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter)ԲҪĴ£
|-AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
|-AbstractApplicationContext#refresh
|-AbstractApplicationContext#finishBeanFactoryInitialization
|-DefaultListableBeanFactory#preInstantiateSingletons
|-AbstractBeanFactory#getBean(String)
|-AbstractBeanFactory#doGetBean
|-DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>)
|-AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])
|-AbstractAutowireCapableBeanFactory#doCreateBean
|-AbstractAutowireCapableBeanFactory#populateBean
|-AutowiredAnnotationBeanPostProcessor#postProcessProperties
|-InjectionMetadata#inject
|-AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
|-DefaultListableBeanFactory#resolveDependency
|-DefaultListableBeanFactory#doResolveDependency
е DefaultListableBeanFactory#doResolveDependency:
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter)
throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
...
// 1\. ͲеbeanClassmapбΪbeanName -> Class
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
...
String autowiredBeanName;
Object instanceCandidate;
// 2\. ҵbeanж1
if (matchingBeans.size() > 1) {
// ȡע
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
return null;
}
}
// 3\. ע ҳmap<beanName, Class>ң
// õbeanClass
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
// class ȡ beanbeanڣᴴbean
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
if (!ClassUtils.isAssignableValue(type, result)) {
throw new BeanNotOfRequiredTypeException(...);
}
return result;
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
bean Ļȡܽ£
磬ڽӿ Interʵ A B߹ϵ£
interface Inter {
}
@Service
class A implements Inter {
}
@Service
class B implements Inter {
}
C Уע Inter ͣ
@Service
class C {
@Autowired
private Inter b;
}
עʱ
Inter.class ңõࣺA.class B.class˶ bean ClassbȻʹ b ϵõ bean Class ҵϵ bean Class ȻB.class ϣB.class Ӧ bean.иС⣺ C ע:
@Service
class C {
@Autowired
private Inter inter;
}
Inter Ϊ inter spring ûΪ inter bean Class עɹ
ʵϣע벻ɹ spring ᱨ쳣ȤСԼԡ
θ class spring лȡӦ bean instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this)ȥ
DependencyDescriptor#resolveCandidate
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
throws BeansException {
// õ AbstractBeanFactory#getBean(String)
return beanFactory.getBean(beanName);
}
൱ֻһУbeanFactory.getBean(beanName)عµ
|-AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
|-AbstractApplicationContext#refresh
|-AbstractApplicationContext#finishBeanFactoryInitialization
|-DefaultListableBeanFactory#preInstantiateSingletons
// һεAbstractBeanFactory#getBean
// ʱIJΪbeanObj1
|-AbstractBeanFactory#getBean(String)
|-AbstractBeanFactory#doGetBean
|-DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>)
|-AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])
|-AbstractAutowireCapableBeanFactory#doCreateBean
|-AbstractAutowireCapableBeanFactory#populateBean
|-AutowiredAnnotationBeanPostProcessor#postProcessProperties
|-InjectionMetadata#inject
|-AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
|-DefaultListableBeanFactory#resolveDependency
|-DefaultListableBeanFactory#doResolveDependency
|-DependencyDescriptor#resolveCandidate
// һεAbstractBeanFactory#getBean
// ʱIJΪbeanObj2
|-AbstractBeanFactory#getBean(String)
.. 濪ʼ`beanObj2`ʵʼ
ϵǰԿ
beanObj1 ʱһε AbstractBeanFactory#getBean(String)ڴʱ spring в beanObj1Ϳʼ beanObj1 ĴbeanObj1 ʵɺžͽע룬beanObj1 и BeanObj2 beanObj2ͬ AbstractBeanFactory#getBean(String) spring лȡ beanObj2beanObj2žͽ beanObj2 Ĵ̣ͬҲ beanObj2 ע롢гʼȲ beanObj1 IJƣbeanObj2 ע뵽 beanObj1 BeanObj2 beanObj2 УȻ beanObj1 ĺԿעʱܻʹ bean ʼǰͬʱζdz A Ҫע BB Ҫע Cô A עʱʼ B B ڳʼʱֻʼ C
bean ʵʼҪȷ£
spring ʼ bean ķ AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition):
protected Object initializeBean(final String beanName, final Object bean,
@Nullable RootBeanDefinition mbd) {
// 1\. invokeAwareMethods
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
// 2\. applyBeanPostProcessorsBeforeInitialization
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// ִ spring еôxxxPostProcessor-------@PostConstruct
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 3\. ִ InitializingBean ʼ
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
...
}
if (mbd == null || !mbd.isSynthetic()) {
// 4\. applyBeanPostProcessorsAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
ϴҪ 4
invokeAwareMethods ִ Aware bean ط
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
ϷȽϼͲ˵ˡ
postProcessBeforeInitializationAbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization У
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// úô
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
Ҫ ApplicationContextAwareProcessor#postProcessBeforeInitialization £
@Override
@Nullable
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
// з
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
// װ ʵApplicationContextAware applicationContext
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
ʵǸ XxxAware ֵ ApplicationContextAware ֵҲС
˳һǣ bean У @PostConstruct ע⣺
@PostConstruct
public void test() {
System.out.println("PostConstruct");
}
÷ InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization неãȽϼҲ jdk ķƣͲ˵ˡ
AbstractAutowireCapableBeanFactory#invokeInitMethods :
protected void invokeInitMethods(String beanName, final Object bean,
@Nullable RootBeanDefinition mbd) throws Throwable {
// ִ InitializingBean#afterPropertiesSet
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null ||
!mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// beanʵ InitializingBean ӿڣ afterPropertiesSet()
((InitializingBean) bean).afterPropertiesSet();
}
}
// ִԶijʼxmlУͨ init-method ָķ
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
Ҫ
invokeCustomInitMethod УҲͨ jdk еģͲ˵ˡpostProcessAfterInitializationһҪ BeanPostProcessor#postProcessAfterInitializationе BeanPostProcessor ApplicationListenerDetector:
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
}
else if (Boolean.FALSE.equals(flag)) {
this.singletonNames.remove(beanName);
}
}
return bean;
}
ApplicationListener ģ bean ʵ ApplicationListenerӵ spring ļбġ
Ҫ spring bean ̣ܽ£
ʵ beanָ˳ʼָ factory methodƶϹ췽ȷʽ
ѯעԻЩԻϱע @Autowird/@Value/@Resource
AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ҵ @Autowired@Value עԺͷCommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition Ҵ @Resource עԺͷ* `AutowiredAnnotationBeanPostProcessor.postProcessProperties` `@Autowired``@Value` ע⣬`CommonAnnotationBeanPostProcessor.postProcessProperties` `@Resource` ע
* `@Autowired` ʱȸҵе `Class`жٸעԵƲҷϵ `Class` `beanFactory.getBean(...)` spring ȡҪעĶͨΪӦֵ
4. ʼ bean
1. ִ Aware bean ط
2. `BeanPostProcessor#postProcessBeforeInitialization`
* `ApplicationContextAwareProcessor#postProcessBeforeInitialization` ִ Aware bean ط
* `InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization` д `@PostConstruct` ע
3. ִгʼ
* ִ `InitializingBean#afterPropertiesSet`
* ִԶ `init-method`
4. `BeanPostProcessor#postProcessAfterInitialization`
* `ApplicationListenerDetector#postProcessAfterInitialization` д spring
spring bean Ĵ̾ȷˣ spring ڴ bean ĹУһӵѭⷽĴԲο
ԭӣhttps://my.oschina.net/funcy/blog/4659524 ߸ˮƽд֮ӭָԭףҵתϵȨҵתע