文章目录
Spring bean的实例化源码解析
之前我们已经知道beanDefinition对象的生成,那么它最后如何实例化的呢,我们来看Spring实例化bean的源码。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//省略其他代码
//这次我们着重看到这里的代码。
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
}
}
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//省略部分源码
//看这里
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 之前已经分析过了,这个集合中放入了所有被扫描到的beanDefinition的beanName
//还有另一个map--->beanDefinitionMap 放入了beanName 和 beanDefinition。
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//循环所有的beanName调用
for (String beanName : beanNames) {
//如果有配置父bean,需要把父beanDefinition的属性设置到子beanDefinition中,再去实例化子bean。
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象,单例,非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//bean是否实现了FactoryBean接口,这个接口后面再详细讲
if (isFactoryBean(beanName)) {
//省略
}
else {
//看这里
getBean(beanName);
}
}
}
//实现了SmartInitializingSingleton接口的bean,调用afterSingletonsInstantiated方法。
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
AbstractBeanFactory
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//暂时认为getSingleton就是从缓存(singletonObjects)中拿到实例化完成的bean(讲到循环依赖的时候再来详细分析)
//单例bean实例化完成以后,会放入缓存中,后续再获取就直接从这里拿到bean。
//第一次进来,肯定拿不到
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
//暂时认为这里返回了我们实例化的的bean,等讲到FactoryBean接口的时候再来详细看这个方法
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//多例不允许出现循环依赖,(讲到循环依赖的时候再来分析)
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//如果有父容器的话,获取父beanFactory。
BeanFactory parentBeanFactory = getParentBeanFactory();
//存在父beanFactory,且当前的beanFactory中的beanDefinitionMap没有该beanName对应的beanDefinition
//那么就是用父容器去实例化bean
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//如果有配置父bean,需要把父beanDefinition的属性设置到子beanDefinition中,再去实例化子bean
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//不能是抽象的beanDefinition,否则抛异常
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//beanDefinition配置了依赖的bean(@DependsOn注解或者bean标签depends-on属性),则要先实例化依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
//循环dependsOn不允许
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//记录 bean和被依赖的bean 到Map中
registerDependentBean(dep, beanName);
try {
//实例化被依赖的bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
//单例bean,看这里的代码
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
//暂时认为这里返回了我们实例化的的bean,等讲到FactoryBean接口的时候再来详细看这个方法
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
//多列和scope的还是比较简单的。
//省略部分源码
//返回实例化后的bean
return (T) bean;
}
DefaultSingletonBeanRegistry
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//从缓存中获取到单例对象,第一次进来肯定获取不到
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//向singletonsCurrentlyInCreation集合中放入beanName
//表示该bean正在实例化中
//循环依赖的时候会用到该集合
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//创建单例bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//从singletonsCurrentlyInCreation集合中移除beanName
afterSingletonCreation(beanName);
}
if (newSingleton) {
//bean实例化完成后放入singletonObjects和registeredSingletons中,后续获取bean直接从singletonObjects获取
//移除singletonFactories和earlySingletonObjects的数据
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
AbstractAutowireCapableBeanFactory
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
//省略部分源码
try {
//看这里
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
//返回创建完成的bean
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//看这里,调用构造函数实例化bean,基于构造函数的依赖注入会完成
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//这里收集一些比较重要的注解,
//@Resource @PostConstruct @PreDestroy
//@Autowired @Value
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
//这里讲到循环依赖的时候再来说明
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
//对实例化完成的bean进行属性填充
Object exposedObject = bean;
try {
//ioc依赖注入属性
populateBean(beanName, mbd, instanceWrapper);
//实例化和ioc完成以后
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
//这里讲到循环依赖的时候再来说明
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
//销毁bean的相关代码,不单独开文分析了,这里简单提一下。
//单列的情况下会将bean注册到disposableBeans的map中,为beanName和DisposableBeanAdapter对象(持有原bean实例)的映射
//当调用destroySingletons方法去移除全部单列实例的时候
//从disposableBeans获取全部的beanName去清除spring容器中保存了单例bean相关信息的数据
//disposableBeans集合也会被清除
//DisposableBeanAdapter实现了DisposableBean接口有destroy方法
//当调用destroySingleton方法会调用到DisposableBeanAdapter的destroy方法,首先会调用实现了DestructionAwareBeanPostProcessor接口的bean的postProcessBeforeDestruction方法,然后如果被销毁的bean实现了DisposableBean接口,接着调用bean的destroy方法,最后调用bean标签的destory-method方法或者是@PreDestory标识的方法
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
//返回创建完成的bean
return exposedObject;
}
createBeanInstance方法解析
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//如果bean标签配置了factory-method属性
//或者使用@Bean注解创建bean (@Bean的收集和解析后续再详细讲)
if (mbd.getFactoryMethodName() != null) {
//<bean id="factoryMethodbean" class="demo.FactoryMethodBean"/>
//<bean id="zhangSan" factory-bean="factoryMethodbean" factory-method="factoryMethod1"/>(首先会去实例化factoryMethodbean,再去反射调用factoryMethod1方法,必须是非静态方法)
//<bean id="liSi" class="demo.FactoryMethodBean" factory-method="factoryMethod2"/>(直接反射调用静态方法,必须是静态方法)
//使用反射调用的方法的返回的对象作为bean的实例化对象直接返回
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
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)) {
//构造函数带有参数
//参数类型是被spring管理的bean的类型,会把该参数对应的bean实例化,作为构造函数的入参传入
//最终调用到beanFactory.resolveDependency方法去拿到参数的实例
//构造函数的@Value的依赖注入也在这里,不是去beanfactory中拿实例了,而是从解析的配置文件的对象中拿值(后面讲到配置文件解析再来看@Value的处理)
//参数有了以后,反射调用该构造函数,拿到bean的实例返回
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
//只有无参构造函数,直接反射调用构造函数实例化
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
//拿到所有实现了BeanPostProcessor接口的bean循环调用
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//如果是SmartInstantiationAwareBeanPostProcessor类型
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
//看到AutowiredAnnotationBeanPostProcessor类的实现逻辑
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//可以有多个被@Autowired修饰但是要注解的value值为false(最多有一个为true的,则会找到该构造函数)
//如果都为false,则找到多个构造函数,autowireConstructor方法会根据一定规则调用权重更高的一个
//如果只有一个构造函数可以不需要@Autowired注解修饰,则找不到,但是autowireConstructor会调用该构造函数
//如果有多个构造函数且都没有@Autowired注解修饰,则找不到,必须要有无参构造函数,autowireConstructor方法会调用该无参构造函数
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
applyMergedBeanDefinitionPostProcessors方法解析
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
//获取所有实现了BeanPostProcessor接口的实例
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//如果是MergedBeanDefinitionPostProcessor类型
if (bp instanceof MergedBeanDefinitionPostProcessor) {
//CommonAnnotationBeanPostProcessor收集@PostConstruct @PreDestory @Resource
//AutowiredAnnotationBeanPostProcessor收集@Autowired @Value
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
先看AutowiredAnnotationBeanPostProcessor的postProcessMergedBeanDefinition方法,就是收集该bean的@Autowired注解和@Value注解
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
//看这里
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
//第一次进来,获取不到。
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
//收集类中@Autowired @Value的信息
metadata = buildAutowiringMetadata(clazz);
//放入缓存中,后续可以直接获取
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
return InjectionMetadata.EMPTY;
}
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
//收集需要依赖注入的@Autowired和@Value注解
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
//查找类中的所有字段,是否存在注解
ReflectionUtils.doWithLocalFields(targetClass, field -> {
MergedAnnotation<?> ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
//获取注解的required属性
boolean required = determineRequiredStatus(ann);
//含有注解的field包装为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())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
//含有注解的method包装为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);
}
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
//获取类中所有的注解
MergedAnnotations annotations = MergedAnnotations.from(ao);
//autowiredAnnotationTypes容器中是Autowired.class和Value.class
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
MergedAnnotation<?> annotation = annotations.get(type);
if (annotation.isPresent()) {
return annotation;
}
}
return null;
}
再来看CommonAnnotationBeanPostProcessor的postProcessMergedBeanDefinition方法。
收集该bean的@Resource注解(该注解也能完成依赖注入,不同于@Autowired是spring的注解,@Resource是jdk的注解)和@PostConstruct,@PreDestroy注解
实际上和AutowiredAnnotationBeanPostProcessor类似的逻辑,就不再重复讲解了。
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
//收集@PostConstruct和@PreDestroy注解。
//收集到的元信息包装为LifecycleMetadata
//initMethods集合中放入@PostConstruct标识的方法
//destroyMethods集合中放入@PreDestroy标识的方法
super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
//收集@Resource注解,收集到的元信息包装为ResourceElement
InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
//initAnnotationType为PostConstruct.class
setInitAnnotationType(PostConstruct.class);
//destroyAnnotationType为PreDestroy.class
setDestroyAnnotationType(PreDestroy.class);
ignoreResourceType("javax.xml.ws.WebServiceContext");
}
populateBean方法解析
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//省略部分代码
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
//获取所有实现了BeanPostProcessor接口的bean
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//如果是InstantiationAwareBeanPostProcessor接口
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//调用该接口的postProcessAfterInstantiation具体实现,如果返回为false,则中止依赖注入过程
//实现该接口可以自己对bean的属性进行填充,而不去走依赖注入的代码
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//默认为AUTOWIRE_NO(需要加上注解去指定注入属性),可以修改beanDefinition的AutowireMode使得所有beanDefinition的PropertyValue和类中的属性(不用加注解了)通过ByName或者ByType去寻找对应的bean,然后赋值到PropertyValue属性中。
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
//当向容器中注册了实现了BeanPostProcessor接口的bean时为ture。显然为true。
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
//看这里
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//获取所有实现了BeanPostProcessor接口的bean
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//CommonAnnotationBeanPostProcessor完成@Resource注解的依赖注入
//AutowiredAnnotationBeanPostProcessor完成@Autowired的依赖注入
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//调用具体实现完成依赖注入
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
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);
}
//将beanDefinition的PropertyValue属性赋值到对象中,反射调用set方法
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
先看AutowiredAnnotationBeanPostProcessor的postProcessProperties方法
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
//获取到之前收集到的注解信息
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
//看这里,分为field和method两种注入方式
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
以AutowiredFieldElement的inject为例,AutowiredMethodElementd的逻辑也差不多就不重复说明了
@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 {
//封装需要依赖注入的field
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 {
//@Autowired的依赖注入,获取到依赖的bean实例
//@Value的依赖注入也在这里做的,我们后面讲到配置文件解析再来提一下
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
//注册原Bean和被依赖的bean到map中
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
//将依赖的bean反射赋值到filed
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
再来是CommonAnnotationBeanPostProcessor的postProcessProperties方法,这里的metadata为ResourceElement类型
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
//之前收集过了,现在直接从缓存拿
InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
try {
//看这里
metadata.inject(bean, beanName, pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
}
return pvs;
}
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable {
//字段依赖注入
if (this.isField) {
Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
//反射设置字段值,getResourceToInject获得依赖注入的bean
field.set(target, getResourceToInject(target, requestingBeanName));
}
//方法依赖注入
else {
if (checkPropertySkipping(pvs)) {
return;
}
try {
Method method = (Method) this.member;
ReflectionUtils.makeAccessible(method);
//反射调用方法
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
getResource(this, requestingBeanName));
}
protected Object getResource(LookupElement element, @Nullable String requestingBeanName)
throws NoSuchBeanDefinitionException {
//省略部分代码
//看这里
return autowireResource(this.resourceFactory, element, requestingBeanName);
}
protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName)
throws NoSuchBeanDefinitionException {
Object resource;
Set<String> autowiredBeanNames;
String name = element.name;
//DefaultListableBeanFactory实现了AbstractBeanFactory接口
if (factory instanceof AutowireCapableBeanFactory) {
AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
DependencyDescriptor descriptor = element.getDependencyDescriptor();
//3个条件
//fallbackToDefaultTypeMatch默认为true
//@Resource如果没有配置name 则isDefaultName为true
//beanFactor是否注册过该bean
if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
autowiredBeanNames = new LinkedHashSet<>();
resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
if (resource == null) {
throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
}
}
else {
//获取到依赖的bean实例
resource = beanFactory.resolveBeanByName(name, descriptor);
autowiredBeanNames = Collections.singleton(name);
}
}
else {
resource = factory.getBean(name, element.lookupType);
autowiredBeanNames = Collections.singleton(name);
}
//DefaultListableBeanFactory实现了AbstractBeanFactory接口
if (factory instanceof ConfigurableBeanFactory) {
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
for (String autowiredBeanName : autowiredBeanNames) {
if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) {
//注册原Bean和被依赖的bean到map中
beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
}
}
}
//返回依赖注入的bean实例
return resource;
}
initializeBean方法解析
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//部分aware接口的调用
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//实现了BeanPostProcessor接口的bean的postProcessBeforeInitialization方法调用
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//InitializingBean接口, bean标签init-method属性
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//实现了BeanPostProcessor接口的bean的postProcessAfterInitialization方法调用
//这里有可能会生成代理对象,讲到aop的时候详细说明
//前面我们已经讲过事件监听的源码了,但是没有讲解这个ApplicationListenerDetector类,这里来提一下
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(String beanName, Object bean) {
//实现了aware接口
if (bean instanceof Aware) {
//实现了BeanNameAware接口
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
//实现了BeanClassLoaderAware接口
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//实现了BeanFactoryAware接口
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//获取实现了BeanPostProcessor接口的bean
for (BeanPostProcessor processor : getBeanPostProcessors()) {
//调用postProcessBeforeInitialization方法。
//这里先看InitDestroyAnnotationBeanPostProcessor,ApplicationContextAwareProcessor
//还有其他很重要的接口后面讲到对应的点上再讲
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
InitDestroyAnnotationBeanPostProcessor的postProcessBeforeInitialization
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//之前已经收集到了@PostConstruct注解的bean的信息
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
//直接反射调用被该注解标识的方法
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}
ApplicationContextAwareProcessor的postProcessBeforeInitialization
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 {
//一堆aware接口,帮助我们方便获取到这些对象
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);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
return bean;
}
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
//如果实现了InitializingBean
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//直接调用afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
//beanDefinition中有initMethodName属性
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//反射调用init-method配置的方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
ApplicationListenerDetector的postProcessAfterInitialization方法
public Object postProcessAfterInitialization(Object bean, String beanName) {
//如果实现了ApplicationListener接口
if (bean instanceof ApplicationListener) {
// potentially not detected as a listener by getBeanNamesForType retrieval
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
// singleton bean (top-level or inner): register on the fly
//将监听者加入到applicationContext的applicationListeners中和多播器的applicationListeners中。
this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
}
else if (Boolean.FALSE.equals(flag)) {
if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
// inner bean with other scope - can't reliably process events
logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
"but is not reachable for event multicasting by its containing ApplicationContext " +
"because it does not have singleton scope. Only top-level listener beans are allowed " +
"to be of non-singleton scope.");
}
this.singletonNames.remove(beanName);
}
}
return bean;
}
到此,单例bean的实例化的主体流程就走完了,实例化bean,ioc依赖注入,和各种BeanPostProcessor接口的调用,最后单例bean被放入singletonObjects中,后续可以直接获取到。