/** * Populate the bean instance in the given BeanWrapper with the property values * from the bean definition. * 依赖注入的核心方法 */ @SuppressWarnings("deprecation")// for postProcessPropertyValues protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // 2.bw为空时的处理 if (bw == null) { if (mbd.hasPropertyValues()) { // 2.1 如果bw为空,属性不为空,抛异常,无法将属性值应用于null实例 thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 2.2 如果bw为空,属性也为空,则跳过 return; } }
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 用于标识是否继续之后的属性填充 //这里很有意思,写接口可以让所有类都不能依赖注入 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { // 3.1 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessoribp= (InstantiationAwareBeanPostProcessor) bp; // 3.2 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { // 3.3 如果返回false,将continueWithPropertyPopulation赋值为false,代表要跳过之后的属性填充 //是否需要DI,依赖注入不需要直接返回 return; } } } }
/** * Fill in any missing property values with references to * other beans in this factory if autowire is set to "byName". * 是根据属性名称完成自动依赖注入的 */ protectedvoidautowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 1.寻找bw中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { // 2.校验是否存在beanName=propertyName的bean实例或者BeanDefinition if (containsBean(propertyName)) { // 3.获取propertyName的bean实例对象 Objectbean= getBean(propertyName); // 4.将属性名和属性值添加到pvs pvs.add(propertyName, bean); // 5.注册依赖关系到缓存(beanName依赖propertyName) registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
/** * Register a dependent bean for the given bean, * to be destroyed before the given bean is destroyed. * 注册依赖的bean和bean name的映射关系 * * @param beanName the name of the bean * @param dependentBeanName the name of the dependent bean */ publicvoidregisterDependentBean(String beanName, String dependentBeanName) { // 1.解析别名 StringcanonicalName= canonicalName(beanName);
/** * Abstract method defining "autowire by type" (bean properties by type) behavior. * <p>This is like PicoContainer default, in which there must be exactly one bean * of the property type in the bean factory. This makes bean factories simple to * configure for small namespaces, but doesn't work as well as standard Spring * behavior for bigger applications. * 按类型注入 */ protectedvoidautowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取 TypeConverter 实例 // 使用自定义的 TypeConverter,用于取代默认的 PropertyEditor 机制 TypeConverterconverter= getCustomTypeConverter(); if (converter == null) { converter = bw; } //创建BeanName属性名称集合 Set<String> autowiredBeanNames = newLinkedHashSet<>(4); // 1.寻找bw中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); // 2.遍历所有需要依赖注入的属性 for (String propertyName : propertyNames) { try { PropertyDescriptorpd= bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. if (Object.class != pd.getPropertyType()) { // 3.获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入) MethodParametermethodParam= BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. //如果后置处理器有优先级,则不允许eager init进行类型匹配。 booleaneager= !(bw.getWrappedInstance() instanceof PriorityOrdered); // 4.将MethodParameter的方法参数索引信息封装成DependencyDescriptor DependencyDescriptordesc=newAutowireByTypeDependencyDescriptor(methodParam, eager); // 5.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中 // 当属性存在过个封装 bean 时将会找到所有匹配的 bean 并将其注入 ObjectautowiredArgument= resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { // 6.如果找到了依赖的bean实例,将属性名和bean实例放到pvs中 pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 7.注册依赖关系,beanName依赖autowiredBeanName registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } //8.清空属性名称集合 autowiredBeanNames.clear(); } } catch (BeansException ex) { thrownewUnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
/** * Apply the given property values, resolving any runtime references * to other beans in this bean factory. Must use deep copy, so we * don't permanently modify this property. * 将所有PropertyValues中的属性填充到bean中 */ protectedvoidapplyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { if (pvs.isEmpty()) { return; }
/** * Give a bean a chance to react now all its properties are set, * and a chance to know about its owning bean factory (this object). * This means checking whether the bean implements InitializingBean or defines * a custom init method, and invoking the necessary callback(s) if it does. * 实例化bean后调用InitMethod接口进行初始化 * */ protectedvoidinvokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
/** * Invoke the specified custom init method on the given bean. * Called by invokeInitMethods. * <p>Can be overridden in subclasses for custom resolution of init * methods with arguments. * <p> * 调用自定义的InitMethod方法 */ protectedvoidinvokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { //1. 获取初始化方法名称 StringinitMethodName= mbd.getInitMethodName(); Assert.state(initMethodName != null, "No init method set"); //2. 获取initmethod的反射对象 MethodinitMethod= (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
// 3.如果不存在initMethodName对应的方法,并且是强制执行初始化方法(默认为强制), 则抛出异常 if (initMethod == null) { if (mbd.isEnforceInitMethod()) { thrownewBeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { // 如果设置了非强制,找不到则直接返回 if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } }
/** * Add the given bean to the list of disposable beans in this factory, * registering its DisposableBean interface and/or the given destroy method * to be called on factory shutdown (if applicable). Only applies to singletons. * 注册销毁的bean */ protectedvoidregisterDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContextacc= (System.getSecurityManager() != null ? getAccessControlContext() : null); // 1.mbd的scope不是prototype && 给定的bean需要在关闭时销毁 if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. // 2.单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作: // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法 // 2.1 DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean //注册对应bean的销毁的DisposableBeanAdapter registerDisposableBean(beanName, newDisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... // 3.自定义scope处理 Scopescope=this.scopes.get(mbd.getScope()); if (scope == null) { thrownewIllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, newDisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } }
requiresDestruction
判断给定的 bean 是否需要在关闭时销毁
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Determine whether the given bean requires destruction on shutdown. * <p>The default implementation checks the DisposableBean interface as well as * a specified destroy method and registered DestructionAwareBeanPostProcessors. * 判断给定的 bean 是否需要在关闭时销毁 */ protectedbooleanrequiresDestruction(Object bean, RootBeanDefinition mbd) { // 1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断bean是否有destroy方法 // 2.hasDestructionAwareBeanPostProcessors():判断当前BeanFactory是否注册过DestructionAwareBeanPostProcessor // 3.DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于bean的DestructionAwareBeanPostProcessor return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors())))); }
/** * Create a new DisposableBeanAdapter for the given bean. * 创建一个新的DisposableBeanAdapter */ publicDisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition, List<BeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) {
Assert.notNull(bean, "Disposable bean must not be null"); this.bean = bean; this.beanName = beanName; //如果bean实现了DisposableBean接口 // 1.判断bean是否需要调用DisposableBean的destroy方法 this.invokeDisposableBean = (this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy")); this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed(); this.acc = acc; // 2.拿到自定义的destroy方法名 StringdestroyMethodName= inferDestroyMethodIfNecessary(bean, beanDefinition); if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) && !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) { this.destroyMethodName = destroyMethodName; // 3.拿到自定义的destroy方法,赋值给this.destroyMethod MethoddestroyMethod= determineDestroyMethod(destroyMethodName); if (destroyMethod == null) { if (beanDefinition.isEnforceDestroyMethod()) { // 4.如果destroy方法名为空,并且enforceDestroyMethod为true,则抛出异常 thrownewBeanDefinitionValidationException("Could not find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'"); } } else { // 5.拿到destroy方法的参数类型数组 //获取销毁方法的参数 Class<?>[] paramTypes = destroyMethod.getParameterTypes(); //如果参数>1 直接报错 // 6.如果destroy方法的参数大于1个,则抛出异常 if (paramTypes.length > 1) { thrownewBeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has more than one parameter - not supported as destroy method"); //如果有一个参数 并且不是boolean类型 直接报错 // 7.如果destroy方法的参数为1个,并且该参数的类型不为boolean,则抛出异常 } elseif (paramTypes.length == 1 && boolean.class != paramTypes[0]) { thrownewBeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has a non-boolean parameter - not supported as destroy method"); } //8. 获取该方法的接口方法 destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod); } //9. 设置到全局的destroyMethod this.destroyMethod = destroyMethod; } //10. 找到支持@Destroy注解的postProcessors this.beanPostProcessors = filterPostProcessors(postProcessors, bean); }
finishBeanFactoryInitialization 方法解析的结束,也标志着 Spring IoC 整个构建过程中,重要的内容基本都已经解析完毕。由于工程较为浩大,因此整个系列的文章中,肯定会有各种各样的问题:理解错误的、用词不一致的(有时候用 “BeanDefinition”,有时候用 “bean 定义”)、漏掉的等等,后续如果有时间,可能会在抽空完善一下,尽量减少出现的问题,也欢迎各位同学指正文章中的错误。
另外,本系列文章到目前为止都是单纯的解析 Spring IoC 的源码,之后可能会再补充一些重要的内容,例如:本文提到要写的@Autowire 注解的依赖注入过程、Spring IoC 中的核心类的介绍等。