Spring:源码解读(IOC容器的依赖注入)
来源:互联网 发布:tc编程语言 编辑:程序博客网 时间:2024/05/21 06:22
四、IOC容器的依赖注入
1、依赖注入发生的时间
当Spring IoC容器完成了Bean定义资源的定位、载入和解析注册以后,IoC容器中已经管理类Bean定义的相关数据,但是此时IoC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况发生:
(1).用户第一次通过getBean方法向IoC容索要Bean时,IoC容器触发依赖注入。
(2).当用户在Bean定义资源中为<Bean>元素配置了lazy-init属性,即让容器在解析注册Bean定义时进行预实例化,触发依赖注入。
BeanFactory接口定义了Spring IoC容器的基本功能规范,是Spring IoC容器所应遵守的最底层和最基本的编程规范。BeanFactory接口中定义了几个getBean方法,就是用户向IoC容器索取管理的Bean的方法,我们通过分析其子类的具体实现,理解Spring IoC容器在用户索取Bean时如何完成依赖注入。
在BeanFactory中我们看到getBean(String…)函数,它的具体实现在AbstractBeanFactory中
2、AbstractBeanFactory通过getBean向IoC容器获取被管理的Bean:
AbstractBeanFactory的getBean相关方法的源码如下:
1 //获取IoC容器中指定名称的Bean 2 public Object getBean(String name) throws BeansException { 3 //doGetBean才是真正向IoC容器获取被管理Bean的过程 4 return doGetBean(name, null, null, false); 5 } 6 //获取IoC容器中指定名称和类型的Bean 7 public <T> T getBean(String name, Class<T> requiredType) throws BeansException { 8 //doGetBean才是真正向IoC容器获取被管理Bean的过程 9 return doGetBean(name, requiredType, null, false); 10 } 11 //获取IoC容器中指定名称和参数的Bean 12 public Object getBean(String name, Object... args) throws BeansException { 13 //doGetBean才是真正向IoC容器获取被管理Bean的过程 14 return doGetBean(name, null, args, false); 15 } 16 //获取IoC容器中指定名称、类型和参数的Bean 17 public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { 18 //doGetBean才是真正向IoC容器获取被管理Bean的过程 19 return doGetBean(name, requiredType, args, false); 20 } 21 //真正实现向IoC容器获取Bean的功能,也是触发依赖注入功能的地方 22 @SuppressWarnings("unchecked") 23 protected <T> T doGetBean( 24 final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) 25 throws BeansException { 26 //根据指定的名称获取被管理Bean的名称,剥离指定名称中对容器的相关依赖 27 //如果指定的是别名,将别名转换为规范的Bean名称 28 final String beanName = transformedBeanName(name); 29 Object bean; 30 //先从缓存中取是否已经有被创建过的单态类型的Bean,对于单态模式的Bean整 31 //个IoC容器中只创建一次,不需要重复创建 32 Object sharedInstance = getSingleton(beanName); 33 //IoC容器创建单态模式Bean实例对象 34 if (sharedInstance != null && args == null) { 35 if (logger.isDebugEnabled()) { 36 //如果指定名称的Bean在容器中已有单态模式的Bean被创建,直接返回 37 //已经创建的Bean 38 if (isSingletonCurrentlyInCreation(beanName)) { 39 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 40 "' that is not fully initialized yet - a consequence of a circular reference"); 41 } 42 else { 43 logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); 44 } 45 } 46 //获取给定Bean的实例对象,主要是完成FactoryBean的相关处理 47 //注意:BeanFactory是管理容器中Bean的工厂,而FactoryBean是 48 //创建创建对象的工厂Bean,两者之间有区别 49 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 50 } 51 else {//缓存没有正在创建的单态模式Bean 52 //缓存中已经有已经创建的原型模式Bean,但是由于循环引用的问题导致实 53 //例化对象失败 54 if (isPrototypeCurrentlyInCreation(beanName)) { 55 throw new BeanCurrentlyInCreationException(beanName); 56 } 57 //对IoC容器中是否存在指定名称的BeanDefinition进行检查,首先检查是否 58 //能在当前的BeanFactory中获取的所需要的Bean,如果不能则委托当前容器 59 //的父级容器去查找,如果还是找不到则沿着容器的继承体系向父级容器查找 60 BeanFactory parentBeanFactory = getParentBeanFactory(); 61 //当前容器的父级容器存在,且当前容器中不存在指定名称的Bean 62 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 63 //解析指定Bean名称的原始名称 64 String nameToLookup = originalBeanName(name); 65 if (args != null) { 66 //委派父级容器根据指定名称和显式的参数查找 67 return (T) parentBeanFactory.getBean(nameToLookup, args); 68 } 69 else { 70 //委派父级容器根据指定名称和类型查找 71 return parentBeanFactory.getBean(nameToLookup, requiredType); 72 } 73 } 74 //创建的Bean是否需要进行类型验证,一般不需要 75 if (!typeCheckOnly) { 76 //向容器标记指定的Bean已经被创建 77 markBeanAsCreated(beanName); 78 } 79 //根据指定Bean名称获取其父级的Bean定义,主要解决Bean继承时子类 80 //合并父类公共属性问题 81 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 82 checkMergedBeanDefinition(mbd, beanName, args); 83 //获取当前Bean所有依赖Bean的名称 84 String[] dependsOn = mbd.getDependsOn(); 85 //如果当前Bean有依赖Bean 86 if (dependsOn != null) { 87 for (String dependsOnBean : dependsOn) { 88 //递归调用getBean方法,获取当前Bean的依赖Bean 89 getBean(dependsOnBean); 90 //把被依赖Bean注册给当前依赖的Bean 91 registerDependentBean(dependsOnBean, beanName); 92 } 93 } 94 //创建单态模式Bean的实例对象 95 if (mbd.isSingleton()) { 96 //这里使用了一个匿名内部类,创建Bean实例对象,并且注册给所依赖的对象 97 sharedInstance = getSingleton(beanName, new ObjectFactory() { 98 public Object getObject() throws BeansException { 99 try { 100 //创建一个指定Bean实例对象,如果有父级继承,则合并子//类和父类的定义 101 return createBean(beanName, mbd, args); 102 } 103 catch (BeansException ex) { 104 //显式地从容器单态模式Bean缓存中清除实例对象 105 destroySingleton(beanName); 106 throw ex; 107 } 108 } 109 }); 110 //获取给定Bean的实例对象 111 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 112 } 113 //IoC容器创建原型模式Bean实例对象 114 else if (mbd.isPrototype()) { 115 //原型模式(Prototype)是每次都会创建一个新的对象 116 Object prototypeInstance = null; 117 try { 118 //回调beforePrototypeCreation方法,默认的功能是注册当前创//建的原型对象 119 beforePrototypeCreation(beanName); 120 //创建指定Bean对象实例 121 prototypeInstance = createBean(beanName, mbd, args); 122 } 123 finally { 124 //回调afterPrototypeCreation方法,默认的功能告诉IoC容器指//定Bean的原型对象不再创建了 125 afterPrototypeCreation(beanName); 126 } 127 //获取给定Bean的实例对象 128 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 129 } 130 //要创建的Bean既不是单态模式,也不是原型模式,则根据Bean定义资源中 131 //配置的生命周期范围,选择实例化Bean的合适方法,这种在Web应用程序中 132 //比较常用,如:request、session、application等生命周期 133 else { 134 String scopeName = mbd.getScope(); 135 final Scope scope = this.scopes.get(scopeName); 136 //Bean定义资源中没有配置生命周期范围,则Bean定义不合法 137 if (scope == null) { 138 throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); 139 } 140 try { 141 //这里又使用了一个匿名内部类,获取一个指定生命周期范围的实例 142 Object scopedInstance = scope.get(beanName, new ObjectFactory() { 143 public Object getObject() throws BeansException { 144 beforePrototypeCreation(beanName); 145 try { 146 return createBean(beanName, mbd, args); 147 } 148 finally { 149 afterPrototypeCreation(beanName); 150 } 151 } 152 }); 153 //获取给定Bean的实例对象 154 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 155 } 156 catch (IllegalStateException ex) { 157 throw new BeanCreationException(beanName, 158 "Scope '" + scopeName + "' is not active for the current thread; " + 159 "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", 160 ex); 161 } 162 } 163 } 164 //对创建的Bean实例对象进行类型检查 165 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { 166 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 167 } 168 return (T) bean; 169 }
通过上面对向IoC容器获取Bean方法的分析,我们可以看到在Spring中,如果Bean定义的单态模式(Singleton),则容器在创建之前先从缓存中查找,以确保整个容器中只存在一个实例对象。如果Bean定义的是原型模式(Prototype),则容器每次都会创建一个新的实例对象。除此之外,Bean定义还可以扩展为指定其生命周期范围。
上面的源码只是定义了根据Bean定义的模式,采取的不同创建Bean实例对象的策略,具体的Bean实例对象的创建过程由实现了ObejctFactory接口的匿名内部类的createBean方法完成,ObejctFactory使用委派模式,具体的Bean实例创建过程交由其实现类AbstractAutowireCapableBeanFactory完成,我们继续分析AbstractAutowireCapableBeanFactory的createBean方法的源码,理解其创建Bean实例的具体实现过程。
3、AbstractAutowireCapableBeanFactory创建Bean实例对象:
AbstractAutowireCapableBeanFactory类实现了ObejctFactory接口,创建容器指定的Bean实例对象,同时还对创建的Bean实例对象进行初始化处理。其创建Bean实例对象的方法源码如下:
1 //创建Bean实例对象 2 protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) 3 throws BeanCreationException { 4 if (logger.isDebugEnabled()) { 5 logger.debug("Creating instance of bean '" + beanName + "'"); 6 } 7 //判断需要创建的Bean是否可以实例化,即是否可以通过当前的类加载器加载 8 resolveBeanClass(mbd, beanName); 9 //校验和准备Bean中的方法覆盖 10 try { 11 mbd.prepareMethodOverrides(); 12 } 13 catch (BeanDefinitionValidationException ex) { 14 throw new BeanDefinitionStoreException(mbd.getResourceDescription(), 15 beanName, "Validation of method overrides failed", ex); 16 } 17 try { 18 //如果Bean配置了初始化前和初始化后的处理器,则试图返回一个需要创建//Bean的代理对象 19 Object bean = resolveBeforeInstantiation(beanName, mbd); 20 if (bean != null) { 21 return bean; 22 } 23 } 24 catch (Throwable ex) { 25 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 26 "BeanPostProcessor before instantiation of bean failed", ex); 27 } 28 //创建Bean的入口 29 Object beanInstance = doCreateBean(beanName, mbd, args); 30 if (logger.isDebugEnabled()) { 31 logger.debug("Finished creating instance of bean '" + beanName + "'"); 32 } 33 return beanInstance; 34 } 35 //真正创建Bean的方法 36 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { 37 //封装被创建的Bean对象 38 BeanWrapper instanceWrapper = null; 39 if (mbd.isSingleton()){//单态模式的Bean,先从容器中缓存中获取同名Bean 40 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); 41 } 42 if (instanceWrapper == null) { 43 //创建实例对象 44 instanceWrapper = createBeanInstance(beanName, mbd, args); 45 } 46 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); 47 //获取实例化对象的类型 48 Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); 49 //调用PostProcessor后置处理器 50 synchronized (mbd.postProcessingLock) { 51 if (!mbd.postProcessed) { 52 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 53 mbd.postProcessed = true; 54 } 55 } 56 // Eagerly cache singletons to be able to resolve circular references 57 //向容器中缓存单态模式的Bean对象,以防循环引用 58 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && 59 isSingletonCurrentlyInCreation(beanName)); 60 if (earlySingletonExposure) { 61 if (logger.isDebugEnabled()) { 62 logger.debug("Eagerly caching bean '" + beanName + 63 "' to allow for resolving potential circular references"); 64 } 65 //这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用 66 addSingletonFactory(beanName, new ObjectFactory() { 67 public Object getObject() throws BeansException { 68 return getEarlyBeanReference(beanName, mbd, bean); 69 } 70 }); 71 } 72 //Bean对象的初始化,依赖注入在此触发 73 //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean 74 Object exposedObject = bean; 75 try { 76 //将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象 77 populateBean(beanName, mbd, instanceWrapper); 78 if (exposedObject != null) { 79 //初始化Bean对象 80 exposedObject = initializeBean(beanName, exposedObject, mbd); 81 } 82 } 83 catch (Throwable ex) { 84 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { 85 throw (BeanCreationException) ex; 86 } 87 else { 88 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); 89 } 90 } 91 if (earlySingletonExposure) { 92 //获取指定名称的已注册的单态模式Bean对象 93 Object earlySingletonReference = getSingleton(beanName, false); 94 if (earlySingletonReference != null) { 95 //根据名称获取的以注册的Bean和正在实例化的Bean是同一个 96 if (exposedObject == bean) { 97 //当前实例化的Bean初始化完成 98 exposedObject = earlySingletonReference; 99 } 100 //当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象 101 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { 102 String[] dependentBeans = getDependentBeans(beanName); 103 Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); 104 //获取当前Bean所依赖的其他Bean 105 for (String dependentBean : dependentBeans) { 106 //对依赖Bean进行类型检查 107 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { 108 actualDependentBeans.add(dependentBean); 109 } 110 } 111 if (!actualDependentBeans.isEmpty()) { 112 throw new BeanCurrentlyInCreationException(beanName, 113 "Bean with name '" + beanName + "' has been injected into other beans [" + 114 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + 115 "] in its raw version as part of a circular reference, but has eventually been " + 116 "wrapped. This means that said other beans do not use the final version of the " + 117 "bean. This is often the result of over-eager type matching - consider using " + 118 "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); 119 } 120 } 121 } 122 } 123 //注册完成依赖注入的Bean 124 try { 125 registerDisposableBeanIfNecessary(beanName, bean, mbd); 126 } 127 catch (BeanDefinitionValidationException ex) { 128 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); 129 } 130 return exposedObject; }
通过对方法源码的分析,我们看到具体的依赖注入实现在以下两个方法中:
(1).createBeanInstance:生成Bean所包含的java对象实例。
(2).populateBean :对Bean属性的依赖注入进行处理。
下面继续分析这两个方法的代码实现。
4、createBeanInstance方法创建Bean的java实例对象:
在createBeanInstance方法中,根据指定的初始化策略,使用静态工厂、工厂方法或者容器的自动装配特性生成java实例对象,创建对象的源码如下:
1 //创建Bean的实例对象 2 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { 3 //检查确认Bean是可实例化的 4 Class beanClass = resolveBeanClass(mbd, beanName); 5 //使用工厂方法对Bean进行实例化 6 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { 7 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 8 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); 9 } 10 if (mbd.getFactoryMethodName() != null) { 11 //调用工厂方法实例化 12 return instantiateUsingFactoryMethod(beanName, mbd, args); 13 } 14 //使用容器的自动装配方法进行实例化 15 boolean resolved = false; 16 boolean autowireNecessary = false; 17 if (args == null) { 18 synchronized (mbd.constructorArgumentLock) { 19 if (mbd.resolvedConstructorOrFactoryMethod != null) { 20 resolved = true; 21 autowireNecessary = mbd.constructorArgumentsResolved; 22 } 23 } 24 } 25 if (resolved) { 26 if (autowireNecessary) { 27 //配置了自动装配属性,使用容器的自动装配实例化 28 //容器的自动装配是根据参数类型匹配Bean的构造方法 29 return autowireConstructor(beanName, mbd, null, null); 30 } 31 else { 32 //使用默认的无参构造方法实例化 33 return instantiateBean(beanName, mbd); 34 } 35 } 36 //使用Bean的构造方法进行实例化 37 Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); 38 if (ctors != null || 39 mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || 40 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { 41 //使用容器的自动装配特性,调用匹配的构造方法实例化 42 return autowireConstructor(beanName, mbd, ctors, args); 43 } 44 //使用默认的无参构造方法实例化 45 return instantiateBean(beanName, mbd); 46 } 47 //使用默认的无参构造方法实例化Bean对象 48 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { 49 try { 50 Object beanInstance; 51 final BeanFactory parent = this; 52 //获取系统的安全管理接口,JDK标准的安全管理API 53 if (System.getSecurityManager() != null) { 54 //这里是一个匿名内置类,根据实例化策略创建实例对象 55 beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { 56 public Object run() { 57 return getInstantiationStrategy().instantiate(mbd, beanName, parent); 58 } 59 }, getAccessControlContext()); 60 } 61 else { 62 //将实例化的对象封装起来 63 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); 64 } 65 BeanWrapper bw = new BeanWrapperImpl(beanInstance); 66 initBeanWrapper(bw); 67 return bw; 68 } 69 catch (Throwable ex) { 70 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); 71 } 72 }
经过对上面的代码分析,我们可以看出,对使用工厂方法和自动装配特性的Bean的实例化相当比较清楚,调用相应的工厂方法或者参数匹配的构造方法即可完成实例化对象的工作,但是对于我们最常使用的默认无参构造方法就需要使用相应的初始化策略(JDK的反射机制或者CGLIB)来进行初始化了,在方法getInstantiationStrategy().instantiate中就具体实现类使用初始策略实例化对象。
5、SimpleInstantiationStrategy类使用默认的无参构造方法创建Bean实例化对象:
在使用默认的无参构造方法创建Bean的实例化对象时,方法getInstantiationStrategy().instantiate调用了SimpleInstantiationStrategy类中的实例化Bean的方法,其源码如下:
1 //使用初始化策略实例化Bean对象 2 public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { 3 //如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法 4 if (beanDefinition.getMethodOverrides().isEmpty()) { 5 Constructor<?> constructorToUse; 6 synchronized (beanDefinition.constructorArgumentLock) { 7 //获取对象的构造方法或工厂方法 8 constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; 9 //如果没有构造方法且没有工厂方法 10 if (constructorToUse == null) { 11 //使用JDK的反射机制,判断要实例化的Bean是否是接口 12 final Class clazz = beanDefinition.getBeanClass(); 13 if (clazz.isInterface()) { 14 throw new BeanInstantiationException(clazz, "Specified class is an interface"); 15 } 16 try { 17 if (System.getSecurityManager() != null) { 18 //这里是一个匿名内置类,使用反射机制获取Bean的构造方法 19 constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() { 20 public Constructor run() throws Exception { 21 return clazz.getDeclaredConstructor((Class[]) null); 22 } 23 }); 24 } 25 else { 26 constructorToUse = clazz.getDeclaredConstructor((Class[]) null); 27 } 28 beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; 29 } 30 catch (Exception ex) { 31 throw new BeanInstantiationException(clazz, "No default constructor found", ex); 32 } 33 } 34 } 35 //使用BeanUtils实例化,通过反射机制调用”构造方法.newInstance(arg)”来进行实例化 36 return BeanUtils.instantiateClass(constructorToUse); 37 } 38 else { 39 //使用CGLIB来实例化对象 40 return instantiateWithMethodInjection(beanDefinition, beanName, owner); 41 } }
通过上面的代码分析,我们看到了如果Bean有方法被覆盖了,则使用JDK的反射机制进行实例化,否则,使用CGLIB进行实例化。
instantiateWithMethodInjection方法调用SimpleInstantiationStrategy的子类CglibSubclassingInstantiationStrategy使用CGLIB来进行初始化,其源码如下:
1 //使用CGLIB进行Bean对象实例化 2 public Object instantiate(Constructor ctor, Object[] args) { 3 //CGLIB中的类 4 Enhancer enhancer = new Enhancer(); 5 //将Bean本身作为其基类 6 enhancer.setSuperclass(this.beanDefinition.getBeanClass()); 7 enhancer.setCallbackFilter(new CallbackFilterImpl()); 8 enhancer.setCallbacks(new Callback[] { 9 NoOp.INSTANCE, 10 new LookupOverrideMethodInterceptor(), 11 new ReplaceOverrideMethodInterceptor() 12 }); 13 //使用CGLIB的create方法生成实例对象 14 return (ctor == null) ? 15 enhancer.create() : 16 enhancer.create(ctor.getParameterTypes(), args); 17 }
CGLIB是一个常用的字节码生成器的类库,它提供了一系列API实现java字节码的生成和转换功能。我们在学习JDK的动态代理时都知道,JDK的动态代理只能针对接口,如果一个类没有实现任何接口,要对其进行动态代理只能使用CGLIB。
6、populateBean方法对Bean属性的依赖注入:
在第3步的分析中我们已经了解到Bean的依赖注入分为以下两个过程:
(1).createBeanInstance:生成Bean所包含的java对象实例。
(2).populateBean :对Bean属性的依赖注入进行处理。
第4、5步中我们已经分析了容器初始化生成Bean所包含的Java实例对象的过程,现在我们继续分析生成对象后,Spring IoC容器是如何将Bean的属性依赖关系注入Bean实例对象中并设置好的,属性依赖注入的代码如下:
1 //将Bean属性设置到生成的实例对象上 2 protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) { 3 //获取容器在解析Bean定义资源时为BeanDefiniton中设置的属性值 4 PropertyValues pvs = mbd.getPropertyValues(); 5 //实例对象为null 6 if (bw == null) { 7 //属性值不为空 8 if (!pvs.isEmpty()) { 9 throw new BeanCreationException( 10 mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); 11 } 12 else { 13 //实例对象为null,属性值也为空,不需要设置属性值,直接返回 14 return; 15 } 16 } 17 //在设置属性之前调用Bean的PostProcessor后置处理器 18 boolean continueWithPropertyPopulation = true; 19 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { 20 for (BeanPostProcessor bp : getBeanPostProcessors()) { 21 if (bp instanceof InstantiationAwareBeanPostProcessor) { 22 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 23 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 24 continueWithPropertyPopulation = false; 25 break; 26 } 27 } 28 } 29 } 30 if (!continueWithPropertyPopulation) { 31 return; 32 } 33 //依赖注入开始,首先处理autowire自动装配的注入 34 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || 35 mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { 36 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); 37 //对autowire自动装配的处理,根据Bean名称自动装配注入 38 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { 39 autowireByName(beanName, mbd, bw, newPvs); 40 } 41 //根据Bean类型自动装配注入 42 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { 43 autowireByType(beanName, mbd, bw, newPvs); 44 } 45 pvs = newPvs; 46 } 47 //检查容器是否持有用于处理单态模式Bean关闭时的后置处理器 48 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); 49 //Bean实例对象没有依赖,即没有继承基类 50 boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); 51 if (hasInstAwareBpps || needsDepCheck) { 52 //从实例对象中提取属性描述符 53 PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw); 54 if (hasInstAwareBpps) { 55 for (BeanPostProcessor bp : getBeanPostProcessors()) { 56 if (bp instanceof InstantiationAwareBeanPostProcessor) { 57 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 58 //使用BeanPostProcessor处理器处理属性值 59 pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 60 if (pvs == null) { 61 return; 62 } 63 } 64 } 65 } 66 if (needsDepCheck) { 67 //为要设置的属性进行依赖检查 68 checkDependencies(beanName, mbd, filteredPds, pvs); 69 } 70 } 71 //对属性进行注入 72 applyPropertyValues(beanName, mbd, bw, pvs); 73 } 74 //解析并注入依赖属性的过程 75 protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { 76 if (pvs == null || pvs.isEmpty()) { 77 return; 78 } 79 //封装属性值 80 MutablePropertyValues mpvs = null; 81 List<PropertyValue> original; 82 if (System.getSecurityManager()!= null) { 83 if (bw instanceof BeanWrapperImpl) { 84 //设置安全上下文,JDK安全机制 85 ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); 86 } 87 } 88 if (pvs instanceof MutablePropertyValues) { 89 mpvs = (MutablePropertyValues) pvs; 90 //属性值已经转换 91 if (mpvs.isConverted()) { 92 try { 93 //为实例化对象设置属性值 94 bw.setPropertyValues(mpvs); 95 return; 96 } 97 catch (BeansException ex) { 98 throw new BeanCreationException( 99 mbd.getResourceDescription(), beanName, "Error setting property values", ex); 100 } 101 } 102 //获取属性值对象的原始类型值 103 original = mpvs.getPropertyValueList(); 104 } 105 else { 106 original = Arrays.asList(pvs.getPropertyValues()); 107 } 108 //获取用户自定义的类型转换 109 TypeConverter converter = getCustomTypeConverter(); 110 if (converter == null) { 111 converter = bw; 112 } 113 //创建一个Bean定义属性值解析器,将Bean定义中的属性值解析为Bean实例对象 114 //的实际值 115 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); 116 //为属性的解析值创建一个拷贝,将拷贝的数据注入到实例对象中 117 List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size()); 118 boolean resolveNecessary = false; 119 for (PropertyValue pv : original) { 120 //属性值不需要转换 121 if (pv.isConverted()) { 122 deepCopy.add(pv); 123 } 124 //属性值需要转换 125 else { 126 String propertyName = pv.getName(); 127 //原始的属性值,即转换之前的属性值 128 Object originalValue = pv.getValue(); 129 //转换属性值,例如将引用转换为IoC容器中实例化对象引用 130 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); 131 //转换之后的属性值 132 Object convertedValue = resolvedValue; 133 //属性值是否可以转换 134 boolean convertible = bw.isWritableProperty(propertyName) && 135 !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); 136 if (convertible) { 137 //使用用户自定义的类型转换器转换属性值 138 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); 139 } 140 //存储转换后的属性值,避免每次属性注入时的转换工作 141 if (resolvedValue == originalValue) { 142 if (convertible) { 143 //设置属性转换之后的值 144 pv.setConvertedValue(convertedValue); 145 } 146 deepCopy.add(pv); 147 } 148 //属性是可转换的,且属性原始值是字符串类型,且属性的原始类型值不是 149 //动态生成的字符串,且属性的原始值不是集合或者数组类型 150 else if (convertible && originalValue instanceof TypedStringValue && 151 !((TypedStringValue) originalValue).isDynamic() && 152 !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { 153 pv.setConvertedValue(convertedValue); 154 deepCopy.add(pv); 155 } 156 else { 157 resolveNecessary = true; 158 //重新封装属性的值 159 deepCopy.add(new PropertyValue(pv, convertedValue)); 160 } 161 } 162 } 163 if (mpvs != null && !resolveNecessary) { 164 //标记属性值已经转换过 165 mpvs.setConverted(); 166 } 167 //进行属性依赖注入 168 try { 169 bw.setPropertyValues(new MutablePropertyValues(deepCopy)); 170 } 171 catch (BeansException ex) { 172 throw new BeanCreationException( 173 mbd.getResourceDescription(), beanName, "Error setting property values", ex); 174 } }
分析上述代码,我们可以看出,对属性的注入过程分以下两种情况:
(1).属性值类型不需要转换时,不需要解析属性值,直接准备进行依赖注入。
(2).属性值需要进行类型转换时,如对其他对象的引用等,首先需要解析属性值,然后对解析后的属性值进行依赖注入。
对属性值的解析是在BeanDefinitionValueResolver类中的resolveValueIfNecessary方法中进行的,对属性值的依赖注入是通过bw.setPropertyValues方法实现的,在分析属性值的依赖注入之前,我们先分析一下对属性值的解析过程。
7、BeanDefinitionValueResolver解析属性值:
当容器在对属性进行依赖注入时,如果发现属性值需要进行类型转换,如属性值是容器中另一个Bean实例对象的引用,则容器首先需要根据属性值解析出所引用的对象,然后才能将该引用对象注入到目标实例对象的属性上去,对属性进行解析的由resolveValueIfNecessary方法实现,其源码如下:
1 //解析属性值,对注入类型进行转换 2 public Object resolveValueIfNecessary(Object argName, Object value) { 3 //对引用类型的属性进行解析 4 if (value instanceof RuntimeBeanReference) { 5 RuntimeBeanReference ref = (RuntimeBeanReference) value; 6 //调用引用类型属性的解析方法 7 return resolveReference(argName, ref); 8 } 9 //对属性值是引用容器中另一个Bean名称的解析 10 else if (value instanceof RuntimeBeanNameReference) { 11 String refName = ((RuntimeBeanNameReference) value).getBeanName(); 12 refName = String.valueOf(evaluate(refName)); 13 //从容器中获取指定名称的Bean 14 if (!this.beanFactory.containsBean(refName)) { 15 throw new BeanDefinitionStoreException( 16 "Invalid bean name '" + refName + "' in bean reference for " + argName); 17 } 18 return refName; 19 } 20 //对Bean类型属性的解析,主要是Bean中的内部类 21 else if (value instanceof BeanDefinitionHolder) { 22 BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value; 23 return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition()); 24 } 25 else if (value instanceof BeanDefinition) { 26 BeanDefinition bd = (BeanDefinition) value; 27 return resolveInnerBean(argName, "(inner bean)", bd); 28 } 29 //对集合数组类型的属性解析 30 else if (value instanceof ManagedArray) { 31 ManagedArray array = (ManagedArray) value; 32 //获取数组的类型 33 Class elementType = array.resolvedElementType; 34 if (elementType == null) { 35 //获取数组元素的类型 36 String elementTypeName = array.getElementTypeName(); 37 if (StringUtils.hasText(elementTypeName)) { 38 try { 39 //使用反射机制创建指定类型的对象 40 elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader()); 41 array.resolvedElementType = elementType; 42 } 43 catch (Throwable ex) { 44 throw new BeanCreationException( 45 this.beanDefinition.getResourceDescription(), this.beanName, 46 "Error resolving array type for " + argName, ex); 47 } 48 } 49 //没有获取到数组的类型,也没有获取到数组元素的类型,则直接设置数 50 //组的类型为Object 51 else { 52 elementType = Object.class; 53 } 54 } 55 //创建指定类型的数组 56 return resolveManagedArray(argName, (List<?>) value, elementType); 57 } 58 //解析list类型的属性值 59 else if (value instanceof ManagedList) { 60 return resolveManagedList(argName, (List<?>) value); 61 } 62 //解析set类型的属性值 63 else if (value instanceof ManagedSet) { 64 return resolveManagedSet(argName, (Set<?>) value); 65 } 66 //解析map类型的属性值 67 else if (value instanceof ManagedMap) { 68 return resolveManagedMap(argName, (Map<?, ?>) value); 69 } 70 //解析props类型的属性值,props其实就是key和value均为字符串的map 71 else if (value instanceof ManagedProperties) { 72 Properties original = (Properties) value; 73 //创建一个拷贝,用于作为解析后的返回值 74 Properties copy = new Properties(); 75 for (Map.Entry propEntry : original.entrySet()) { 76 Object propKey = propEntry.getKey(); 77 Object propValue = propEntry.getValue(); 78 if (propKey instanceof TypedStringValue) { 79 propKey = evaluate((TypedStringValue) propKey); 80 } 81 if (propValue instanceof TypedStringValue) { 82 propValue = evaluate((TypedStringValue) propValue); 83 } 84 copy.put(propKey, propValue); 85 } 86 return copy; 87 } 88 //解析字符串类型的属性值 89 else if (value instanceof TypedStringValue) { 90 TypedStringValue typedStringValue = (TypedStringValue) value; 91 Object valueObject = evaluate(typedStringValue); 92 try { 93 //获取属性的目标类型 94 Class<?> resolvedTargetType = resolveTargetType(typedStringValue); 95 if (resolvedTargetType != null) { 96 //对目标类型的属性进行解析,递归调用 97 return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType); 98 } 99 //没有获取到属性的目标对象,则按Object类型返回 100 else { 101 return valueObject; 102 } 103 } 104 catch (Throwable ex) { 105 throw new BeanCreationException( 106 this.beanDefinition.getResourceDescription(), this.beanName, 107 "Error converting typed String value for " + argName, ex); 108 } 109 } 110 else { 111 return evaluate(value); 112 } 113 } 114 //解析引用类型的属性值 115 private Object resolveReference(Object argName, RuntimeBeanReference ref) { 116 try { 117 //获取引用的Bean名称 118 String refName = ref.getBeanName(); 119 refName = String.valueOf(evaluate(refName)); 120 //如果引用的对象在父类容器中,则从父类容器中获取指定的引用对象 121 if (ref.isToParent()) { 122 if (this.beanFactory.getParentBeanFactory() == null) { 123 throw new BeanCreationException( 124 this.beanDefinition.getResourceDescription(), this.beanName, 125 "Can't resolve reference to bean '" + refName + 126 "' in parent factory: no parent factory available"); 127 } 128 return this.beanFactory.getParentBeanFactory().getBean(refName); 129 } 130 //从当前的容器中获取指定的引用Bean对象,如果指定的Bean没有被实例化 131 //则会递归触发引用Bean的初始化和依赖注入 132 else { 133 Object bean = this.beanFactory.getBean(refName); 134 //将当前实例化对象的依赖引用对象 135 this.beanFactory.registerDependentBean(refName, this.beanName); 136 return bean; 137 } 138 } 139 catch (BeansException ex) { 140 throw new BeanCreationException( 141 this.beanDefinition.getResourceDescription(), this.beanName, 142 "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex); 143 } 144 } 145 //解析array类型的属性 146 private Object resolveManagedArray(Object argName, List<?> ml, Class elementType) { 147 //创建一个指定类型的数组,用于存放和返回解析后的数组 148 Object resolved = Array.newInstance(elementType, ml.size()); 149 for (int i = 0; i < ml.size(); i++) { 150 //递归解析array的每一个元素,并将解析后的值设置到resolved数组中,索引为i 151 Array.set(resolved, i, 152 resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i))); 153 } 154 return resolved; 155 } 156 //解析list类型的属性 157 private List resolveManagedList(Object argName, List<?> ml) { 158 List<Object> resolved = new ArrayList<Object>(ml.size()); 159 for (int i = 0; i < ml.size(); i++) { 160 //递归解析list的每一个元素 161 resolved.add( 162 resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i))); 163 } 164 return resolved; 165 } 166 //解析set类型的属性 167 private Set resolveManagedSet(Object argName, Set<?> ms) { 168 Set<Object> resolved = new LinkedHashSet<Object>(ms.size()); 169 int i = 0; 170 //递归解析set的每一个元素 171 for (Object m : ms) { 172 resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), m)); 173 i++; 174 } 175 return resolved; 176 } 177 //解析map类型的属性 178 private Map resolveManagedMap(Object argName, Map<?, ?> mm) { 179 Map<Object, Object> resolved = new LinkedHashMap<Object, Object>(mm.size()); 180 //递归解析map中每一个元素的key和value 181 for (Map.Entry entry : mm.entrySet()) { 182 Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey()); 183 Object resolvedValue = resolveValueIfNecessary( 184 new KeyedArgName(argName, entry.getKey()), entry.getValue()); 185 resolved.put(resolvedKey, resolvedValue); 186 } 187 return resolved; 188 }
通过上面的代码分析,我们明白了Spring是如何将引用类型,内部类以及集合类型等属性进行解析的,属性值解析完成后就可以进行依赖注入了,依赖注入的过程就是Bean对象实例设置到它所依赖的Bean对象属性上去,在第7步中我们已经说过,依赖注入是通过bw.setPropertyValues方法实现的,该方法也使用了委托模式,在BeanWrapper接口中至少定义了方法声明,依赖注入的具体实现交由其实现类BeanWrapperImpl来完成,下面我们就分析依BeanWrapperImpl中赖注入相关的源码。
8、BeanWrapperImpl对Bean属性的依赖注入:
BeanWrapperImpl类主要是对容器中完成初始化的Bean实例对象进行属性的依赖注入,即把Bean对象设置到它所依赖的另一个Bean的属性中去,依赖注入的相关源码如下:
1 //实现属性依赖注入功能 2 private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { 3 //PropertyTokenHolder主要保存属性的名称、路径,以及集合的size等信息 4 String propertyName = tokens.canonicalName; 5 String actualName = tokens.actualName; 6 //keys是用来保存集合类型属性的size 7 if (tokens.keys != null) { 8 //将属性信息拷贝 9 PropertyTokenHolder getterTokens = new PropertyTokenHolder(); 10 getterTokens.canonicalName = tokens.canonicalName; 11 getterTokens.actualName = tokens.actualName; 12 getterTokens.keys = new String[tokens.keys.length - 1]; 13 System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); 14 Object propValue; 15 try { 16 //获取属性值,该方法内部使用JDK的内省( Introspector)机制,调用属性//的getter(readerMethod)方法,获取属性的值 17 propValue = getPropertyValue(getterTokens); 18 } 19 catch (NotReadablePropertyException ex) { 20 throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, 21 "Cannot access indexed value in property referenced " + 22 "in indexed property path '" + propertyName + "'", ex); 23 } 24 //获取集合类型属性的长度 25 String key = tokens.keys[tokens.keys.length - 1]; 26 if (propValue == null) { 27 throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, 28 "Cannot access indexed value in property referenced " + 29 "in indexed property path '" + propertyName + "': returned null"); 30 } 31 //注入array类型的属性值 32 else if (propValue.getClass().isArray()) { 33 //获取属性的描述符 34 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); 35 //获取数组的类型 36 Class requiredType = propValue.getClass().getComponentType(); 37 //获取数组的长度 38 int arrayIndex = Integer.parseInt(key); 39 Object oldValue = null; 40 try { 41 //获取数组以前初始化的值 42 if (isExtractOldValueForEditor()) { 43 oldValue = Array.get(propValue, arrayIndex); 44 } 45 //将属性的值赋值给数组中的元素 46 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, 47 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType)); 48 Array.set(propValue, arrayIndex, convertedValue); 49 } 50 catch (IndexOutOfBoundsException ex) { 51 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, 52 "Invalid array index in property path '" + propertyName + "'", ex); 53 } 54 } 55 //注入list类型的属性值 56 else if (propValue instanceof List) { 57 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); 58 //获取list集合的类型 59 Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType( 60 pd.getReadMethod(), tokens.keys.length); 61 List list = (List) propValue; 62 //获取list集合的size 63 int index = Integer.parseInt(key); 64 Object oldValue = null; 65 if (isExtractOldValueForEditor() && index < list.size()) { 66 oldValue = list.get(index); 67 } 68 //获取list解析后的属性值 69 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, 70 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType)); 71 if (index < list.size()) { 72 //为list属性赋值 73 list.set(index, convertedValue); 74 } 75 //如果list的长度大于属性值的长度,则多余的元素赋值为null 76 else if (index >= list.size()) { 77 for (int i = list.size(); i < index; i++) { 78 try { 79 list.add(null); 80 } 81 catch (NullPointerException ex) { 82 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, 83 "Cannot set element with index " + index + " in List of size " + 84 list.size() + ", accessed using property path '" + propertyName + 85 "': List does not support filling up gaps with null elements"); 86 } 87 } 88 list.add(convertedValue); 89 } 90 } 91 //注入map类型的属性值 92 else if (propValue instanceof Map) { 93 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); 94 //获取map集合key的类型 95 Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( 96 pd.getReadMethod(), tokens.keys.length); 97 //获取map集合value的类型 98 Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( 99 pd.getReadMethod(), tokens.keys.length); 100 Map map = (Map) propValue; 101 //解析map类型属性key值 102 Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, 103 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType)); 104 Object oldValue = null; 105 if (isExtractOldValueForEditor()) { 106 oldValue = map.get(convertedMapKey); 107 } 108 //解析map类型属性value值 109 Object convertedMapValue = convertIfNecessary( 110 propertyName, oldValue, pv.getValue(), mapValueType, 111 new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1))); 112 //将解析后的key和value值赋值给map集合属性 113 map.put(convertedMapKey, convertedMapValue); 114 } 115 else { 116 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, 117 "Property referenced in indexed property path '" + propertyName + 118 "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); 119 } 120 } 121 //对非集合类型的属性注入 122 else { 123 PropertyDescriptor pd = pv.resolvedDescriptor; 124 if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { 125 pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); 126 //无法获取到属性名或者属性没有提供setter(写方法)方法 127 if (pd == null || pd.getWriteMethod() == null) { 128 //如果属性值是可选的,即不是必须的,则忽略该属性值 129 if (pv.isOptional()) { 130 logger.debug("Ignoring optional value for property '" + actualName + 131 "' - property not found on bean class [" + getRootClass().getName() + "]"); 132 return; 133 } 134 //如果属性值是必须的,则抛出无法给属性赋值,因为每天提供setter方法异常 135 else { 136 PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); 137 throw new NotWritablePropertyException( 138 getRootClass(), this.nestedPath + propertyName, 139 matches.buildErrorMessage(), matches.getPossibleMatches()); 140 } 141 } 142 pv.getOriginalPropertyValue().resolvedDescriptor = pd; 143 } 144 Object oldValue = null; 145 try { 146 Object originalValue = pv.getValue(); 147 Object valueToApply = originalValue; 148 if (!Boolean.FALSE.equals(pv.conversionNecessary)) { 149 if (pv.isConverted()) { 150 valueToApply = pv.getConvertedValue(); 151 } 152 else { 153 if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { 154 //获取属性的getter方法(读方法),JDK内省机制 155 final Method readMethod = pd.getReadMethod(); 156 //如果属性的getter方法不是public访问控制权限的,即访问控制权限比较严格, 157 //则使用JDK的反射机制强行访问非public的方法(暴力读取属性值) 158 if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && 159 !readMethod.isAccessible()) { 160 if (System.getSecurityManager()!= null) { 161 //匿名内部类,根据权限修改属性的读取控制限制 162 AccessController.doPrivileged(new PrivilegedAction<Object>() { 163 public Object run() { 164 readMethod.setAccessible(true); 165 return null; 166 } 167 }); 168 } 169 else { 170 readMethod.setAccessible(true); 171 } 172 } 173 try { 174 //属性没有提供getter方法时,调用潜在的读取属性值//的方法,获取属性值 175 if (System.getSecurityManager() != null) { 176 oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { 177 public Object run() throws Exception { 178 return readMethod.invoke(object); 179 } 180 }, acc); 181 } 182 else { 183 oldValue = readMethod.invoke(object); 184 } 185 } 186 catch (Exception ex) { 187 if (ex instanceof PrivilegedActionException) { 188 ex = ((PrivilegedActionException) ex).getException(); 189 } 190 if (logger.isDebugEnabled()) { 191 logger.debug("Could not read previous value of property '" + 192 this.nestedPath + propertyName + "'", ex); 193 } 194 } 195 } 196 //设置属性的注入值 197 valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd); 198 } 199 pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue); 200 } 201 //根据JDK的内省机制,获取属性的setter(写方法)方法 202 final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? 203 ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : 204 pd.getWriteMethod()); 205 //如果属性的setter方法是非public,即访问控制权限比较严格,则使用JDK的反射机制, 206 //强行设置setter方法可访问(暴力为属性赋值) 207 if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { 208 //如果使用了JDK的安全机制,则需要权限验证 209 if (System.getSecurityManager()!= null) { 210 AccessController.doPrivileged(new PrivilegedAction<Object>() { 211 public Object run() { 212 writeMethod.setAccessible(true); 213 return null; 214 } 215 }); 216 } 217 else { 218 writeMethod.setAccessible(true); 219 } 220 } 221 final Object value = valueToApply; 222 if (System.getSecurityManager() != null) { 223 try { 224 //将属性值设置到属性上去 225 AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { 226 public Object run() throws Exception { 227 writeMethod.invoke(object, value); 228 return null; 229 } 230 }, acc); 231 } 232 catch (PrivilegedActionException ex) { 233 throw ex.getException(); 234 } 235 } 236 else { 237 writeMethod.invoke(this.object, value); 238 } 239 } 240 catch (TypeMismatchException ex) { 241 throw ex; 242 } 243 catch (InvocationTargetException ex) { 244 PropertyChangeEvent propertyChangeEvent = 245 new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); 246 if (ex.getTargetException() instanceof ClassCastException) { 247 throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); 248 } 249 else { 250 throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); 251 } 252 } 253 catch (Exception ex) { 254 PropertyChangeEvent pce = 255 new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); 256 throw new MethodInvocationException(pce, ex); 257 } 258 } }
通过对上面注入依赖代码的分析,我们已经明白了Spring IoC容器是如何将属性的值注入到Bean实例对象中去的:
(1).对于集合类型的属性,将其属性值解析为目标类型的集合后直接赋值给属性。
(2).对于非集合类型的属性,大量使用了JDK的反射和内省机制,通过属性的getter方法(reader method)获取指定属性注入以前的值,同时调用属性的setter方法(writer method)为属性设置注入后的值。看到这里相信很多人都明白了Spring的setter注入原理。
至此Spring IoC容器对Bean定义资源文件的定位,载入、解析和依赖注入已经全部分析完毕,现在Spring IoC容器中管理了一系列靠依赖关系联系起来的Bean,程序不需要应用自己手动创建所需的对象,Spring IoC容器会在我们使用的时候自动为我们创建,并且为我们注入好相关的依赖,这就是Spring核心功能的控制反转和依赖注入的相关功能。
- Spring:源码解读(IOC容器的依赖注入)
- 8-spring源码3.2.18解读+spring技术内幕(IOC容器的依赖注入(反射+递归调用))
- Spring源码学习IOC(5):IOC容器的依赖注入
- Spring IOC容器的依赖注入(源码角度)
- 深入解读Spring Framework IoC容器(第二弹:依赖注入的方式)
- Ioc容器依赖注入-Spring 源码(2)
- Spring源码阅读(三)—IOC容器依赖注入
- 【Spring源码--IOC容器的实现】(六)Bean的依赖注入
- Spring的IOC容器—依赖注入
- Spring Ioc容器依赖注入
- 深入解读Spring Framework IoC容器(第三弹:依赖注入配置详解)
- Spring IOC源码详解之容器依赖注入
- Spring:源码解读(IOC容器的初始化)
- Spring:源码解读(IOC容器的高级特性)
- spring源码解读 Bean的依赖注入
- IOC容器的依赖注入
- IOC容器的依赖注入
- spring技术内幕5-IoC容器的依赖注入
- 数据结构实验之栈二:一般算术表达式转换成后缀式(栈)
- 将两个文件中的单词(汉字)交叉合并到一个文件中
- 正则表达式
- Java基础——包装类
- tmux linux下终端管理器
- Spring:源码解读(IOC容器的依赖注入)
- iOS10 iMessage 带来了你需要的MessageExtension
- Codeforces #363(Div.2) B.One Bomb
- 在.NET平台下【使用WinForm + MySQL】制作数据库管理软件
- poj2112 Optimal Milking 最大流(含经典最大流问题总结)
- tomcat设置图片服务器
- (NYoj 237)游戏高手的烦恼 --二部图最大匹配,匈牙利算法
- 第52课:spark的新解析引擎catalyst源码中的外部数据源、缓存及其他
- 数据结构之栈进制转换 (sdut oj 1252)