【Spring源码--IOC容器的实现】(六)Bean的依赖注入
2016-08-24 10:01
1161 查看
前言:
1.上一篇文章已经分析bean对象的生成,在此基础上,本文将分析Spring怎么把这些bean对象的依赖关系设置好,完成依赖注入的过程。2.依赖注入的过程大致可以分为两部分:(1).bean属性的解析;(2).bean属性的注入。
3.依赖注入很多内容都是从BeanDefinition中取到的,所以BeanDefinition的载入和解析非常重要,最好结合着前面的文章一块看。【SpringIOC源码--IOC容器实现】(三)BeanDefinition的载入和解析【I】、【SpringIOC源码--IOC容器实现】(三)BeanDefinition的载入和解析【II】。
Bean的依赖注入
Bean属性的解析
在讨论Bean的依赖注入时,我们先回到AbstractAutowireCapableBeanFactory类的doCreateBean方法。在这里我们有两个方法,一个是createBeanInstance生成对象,一个是populateBean对象实例化,也就是我们要的依赖注入,来看下简略代码:代码1.1:AbstractAutowireCapableBeanFactory类的doCreateBean方法:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { BeanWrapper instanceWrapper = null; ... if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } ... Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd); } } ... return exposedObject; }代码我们已经找到了,现在就进入populateBean方法具体来看看其实现:
代码1.2:AbstractAutowireCapableBeanFactory类的populateBean方法:
protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) { //获取容器在解析Bean定义的时候的属性值 PropertyValues pvs = mbd.getPropertyValues(); if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { //实例对象为null,属性值也为空,不需要设置属性值,直接返回 return; } } //在设置属性之前调用Bean的PostProcessor后置处理器 boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } //依赖注入开始,首先处理autowire自动装配的注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); //对autowire自动装配的处理,根据Bean名称自动装配注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } //根据Bean类型自动装配注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } //检查容器是否持有用于处理单态模式Bean关闭时的后置处理器 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //Bean实例对象没有依赖,即没有继承基类 boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { //从实例对象中提取属性描述符 PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //使用BeanPostProcessor处理器处理属性值 pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { //为要设置的属性进行依赖检查 checkDependencies(beanName, mbd, filteredPds, pvs); } } //对属性进行注入 applyPropertyValues(beanName, mbd, bw, pvs); }看这块代码有几点我们要明确:
这里包括后面所讲的内容:全部是bean在xml中的定义的内容,我们平时用的@Resource @Autowired并不是在这里解析的,那些属于Spring注解的内容。
这里的autowire跟@Autowired不一样,autowire是Spring配置文件中的一个配置,@Autowired是一个注解。
<bean id="personFactory" class="com.xx.PersonFactory" autowire="byName">
后置处理器那块内容,我们先不研究,先走主线,看对属性注入。【一般Spring不建议autowire的配置,所以不再看该源码】
所以我们继续看applyPropertyValues方法:
代码1.3:AbstractAutowireCapableBeanFactory类的applyPropertyValues方法
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { if (pvs == null || pvs.isEmpty()) { return; } MutablePropertyValues mpvs = null;//封装属性值 List<PropertyValue> original; if (System.getSecurityManager()!= null) { if (bw instanceof BeanWrapperImpl) { //设置安全上下文,JDK安全机制 ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } } if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; //属性值已经转换 if (mpvs.isConverted()) { try { //为实例化对象设置属性值 bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } //获取属性值对象的原始类型值 original = mpvs.getPropertyValueList(); } else { original = Arrays.asList(pvs.getPropertyValues()); } //获取用户自定义的类型转换 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } //创建一个Bean定义属性值解析器,将Bean定义中的属性值解析为Bean实例对象的实际值 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); //为属性的解析值创建一个拷贝,将拷贝的数据注入到实例对象中 List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size()); boolean resolveNecessary = false; for (PropertyValue pv : original) { //属性值不需要转换 if (pv.isConverted()) { deepCopy.add(pv); } else {//属性值需要转换 String propertyName = pv.getName(); Object originalValue = pv.getValue();//原始值 //转换属性值,例如将引用转换为IoC容器中实例化对象引用 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); Object convertedValue = resolvedValue;//转换后的值 //属性值是否可以转换 boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); if (convertible) { //如果还可以转换,使用用户自定义的类型转换器转换属性值 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } //存储转换后的属性值,避免每次属性注入时的转换工作 if (resolvedValue == originalValue) { if (convertible) { //设置属性转换之后的值 pv.setConvertedValue(convertedValue); } deepCopy.add(pv); } //属性是可转换的,且属性原始值是字符串类型,且属性的原始类型值不是动态生成的字符串,且属性的原始值不是集合或者数组类型 else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { pv.setConvertedValue(convertedValue); deepCopy.add(pv); } else { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { //标记属性值已经转换过 mpvs.setConverted(); } //进行属性依赖注入 try { bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } }我们简单来看下这个代码的执行顺序:首先看属性是否已经是符合注入标准的类型MutablePropertyValues,如果是就直接开始注入-->否则,判断属性是否需要转换解析,需要的话则进行解析-->解析完成,开始注入。这里有一点要回忆一下,大家可记得我们在Beandefinition载入和解析的时候,对于Property元素及子元素做了一些操作,比如我们ref被解析成RuntimeBeanReference,list被解析成MangedList。那么,我们当时说了,这么做是为了把bean的配置解析成Spring能够认识的内部结构,所以这些内部结构现在就要被我们用来依赖注入了,Spring就是从这些结构中完成对属性的转换。
所以我们有必要去看下Spring如何解析属性值,来看代码:
代码1.4:BeanDefinitionValueResolver类的resolveValueIfNecessary方法:
public Object resolveValueIfNecessary(Object argName, Object value) { //对引用类型的属性进行解析 if (value instanceof RuntimeBeanReference) { RuntimeBeanReference ref = (RuntimeBeanReference) value; return resolveReference(argName, ref); } //对属性值是引用容器中另一个Bean名称的解析 else if (value instanceof RuntimeBeanNameReference) { String refName = ((RuntimeBeanNameReference) value).getBeanName(); refName = String.valueOf(evaluate(refName)); if (!this.beanFactory.containsBean(refName)) { throw new BeanDefinitionStoreException( "Invalid bean name '" + refName + "' in bean reference for " + argName); } return refName; } //对Bean类型属性的解析,主要是Bean中的内部类 else if (value instanceof BeanDefinitionHolder) { // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value; return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition()); } else if (value instanceof BeanDefinition) { // Resolve plain BeanDefinition, without contained name: use dummy name. BeanDefinition bd = (BeanDefinition) value; return resolveInnerBean(argName, "(inner bean)", bd); } //对集合数组类型的属性解析 else if (value instanceof ManagedArray) { ManagedArray array = (ManagedArray) value; Class elementType = array.resolvedElementType;//获取数组的类型 if (elementType == null) { String elementTypeName = array.getElementTypeName();//获取数组元素的类型 if (StringUtils.hasText(elementTypeName)) { try { //使用反射机制创建指定类型的对象 elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader()); array.resolvedElementType = elementType; } catch (Throwable ex) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error resolving array type for " + argName, ex); } } else { //没有获取到数组的类型,也没有获取到数组元素的类型,则直接设置数组的类型为Object elementType = Object.class; } } return resolveManagedArray(argName, (List<?>) value, elementType); } //解析list类型的属性值 else if (value instanceof ManagedList) { return resolveManagedList(argName, (List<?>) value); } //解析set类型的属性值 else if (value instanceof ManagedSet) { return resolveManagedSet(argName, (Set<?>) value); } //解析map类型的属性值 else if (value instanceof ManagedMap) { return resolveManagedMap(argName, (Map<?, ?>) value); } //解析props类型的属性值,props其实就是key和value均为字符串的map else if (value instanceof ManagedProperties) { Properties original = (Properties) value; Properties copy = new Properties(); for (Map.Entry propEntry : original.entrySet()) { Object propKey = propEntry.getKey(); Object propValue = propEntry.getValue(); if (propKey instanceof TypedStringValue) { propKey = evaluate((TypedStringValue) propKey); } if (propValue instanceof TypedStringValue) { propValue = evaluate((TypedStringValue) propValue); } copy.put(propKey, propValue); } return copy; } //解析字符串类型的属性值 else if (value instanceof TypedStringValue) { // Convert value to target type here. TypedStringValue typedStringValue = (TypedStringValue) value; Object valueObject = evaluate(typedStringValue); try { Class<?> resolvedTargetType = resolveTargetType(typedStringValue); if (resolvedTargetType != null) { return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType); } else { return valueObject; } } catch (Throwable ex) { // Improve the message by showing the context. throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error converting typed String value for " + argName, ex); } } else { return evaluate(value); } }从上面的代码我们可以看到,这里的转换几乎完全跟BeanDefinitionParserDelegate中的parserPropertySubElement方法中对应,那里是为了将bean的配置解析成Spring内部结构,这里由于我们bean已经创建完成,所以我们需要将具体的属性值给赋值上真正的内容(比如引用类型,这时候就要真正的给一个bean实例)。
我们可以看到,这里是根据不同的属性类型,分别进入了不同的方法,我们简单举几个例子看下:
代码1.5:BeanDefinitionValueResolver类的属性解析举例
private Object resolveReference(Object argName, RuntimeBeanReference ref) { try { //获取引用的Bean名称 String refName = ref.getBeanName(); refName = String.valueOf(evaluate(refName)); //如果引用的对象在父类容器中,则从父类容器中获取指定的引用对象 if (ref.isToParent()) { if (this.beanFactory.getParentBeanFactory() == null) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Can't resolve reference to bean '" + refName + "' in parent factory: no parent factory available"); } return this.beanFactory.getParentBeanFactory().getBean(refName); } //从当前的容器中获取指定的引用Bean对象,如果指定的Bean没有被实例化则会递归触发引用Bean的初始化和依赖注入 else { Object bean = this.beanFactory.getBean(refName); //将当前实例化对象的依赖引用对象 this.beanFactory.registerDependentBean(refName, this.beanName); return bean; } } catch (BeansException ex) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex); } } //解析array类型的属性 private Object resolveManagedArray(Object argName, List<?> ml, Class elementType) { //创建一个指定类型的数组,用于存放和返回解析后的数组 Object resolved = Array.newInstance(elementType, ml.size()); for (int i = 0; i < ml.size(); i++) { //递归解析array的每一个元素,并将解析后的值设置到resolved数组中,索引为i Array.set(resolved, i, resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i))); } return resolved; } //解析list类型的属性 private List resolveManagedList(Object argName, List<?> ml) { List<Object> resolved = new ArrayList<Object>(ml.size()); for (int i = 0; i < ml.size(); i++) { //递归解析list的每一个元素 resolved.add( resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i))); } return resolved; } //解析set类型的属性 private Set resolveManagedSet(Object argName, Set<?> ms) { Set<Object> resolved = new LinkedHashSet<Object>(ms.size()); int i = 0; //递归解析set的每一个元素 for (Object m : ms) { resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), m)); i++; } return resolved; } //解析map类型的属性 private Map resolveManagedMap(Object argName, Map<?, ?> mm) { Map<Object, Object> resolved = new LinkedHashMap<Object, Object>(mm.size()); //递归解析map中每一个元素的key和value for (Map.Entry entry : mm.entrySet()) { Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey()); Object resolvedValue = resolveValueIfNecessary( new KeyedArgName(argName, entry.getKey()), entry.getValue()); resolved.put(resolvedKey, resolvedValue); } return resolved; }
上面的代码我们可以从以下几个点来理解:
引用类型的解析:如果引用的对象在父类容器中,则从父类容器中获取指定的引用对象 ,从当前容器取,如果对象没有创建,则递归调用getBean。
其他类型的解析:如list,递归解析list的每一个元素,又走了一遍resolveValueIfNecessary方法,也就是说如果list里面也是配置的ref,那么会递归调用到对引用类型解析。注意这里的递归调用。
bean属性的注入
OK,通过上面的源码分析,我们已经得到了解析好的属性值,也就是说这时候的属性里面就是具体的对象,String等内容了。所以这时候我们就可以对属性进行注入了。在applyPropertyValues方法中,我们可以看到bw.setPropertyValues方法,我们看到的是BeanWrapper.setPropertyValues,但是当我们点进去确实来到了AbstractPropertyAccessor类的方法中,原因是:BeanWrapper继承了PropertyAccessor接口,而AbstractPropertyAccessor实现了PropertyAccessor接口,这里就是运用了组合复用的设计模式。我们先来跟一下这个方法,然后找到具体的实现类。代码1.6:AbstractPropertyAccessor类的setPropertyValues方法
//该方法--调用入口 public void setPropertyValues(PropertyValues pvs) throws BeansException { setPropertyValues(pvs, false, false); } public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid) throws BeansException { List<PropertyAccessException> propertyAccessExceptions = null; //得到属性列表 List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ? ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues())); for (PropertyValue pv : propertyValues) { try { //属性注入 setPropertyValue(pv); } catch (NotWritablePropertyException ex) { if (!ignoreUnknown) { throw ex; } } catch (NullValueInNestedPathException ex) { if (!ignoreInvalid) { throw ex; } } catch (PropertyAccessException ex) { if (propertyAccessExceptions == null) { propertyAccessExceptions = new LinkedList<PropertyAccessException>(); } propertyAccessExceptions.add(ex); } } if (propertyAccessExceptions != null) { PropertyAccessException[] paeArray = propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]); throw new PropertyBatchUpdateException(paeArray); } }上面代码的作用就是得到属性列表,并对每一个属性进行注入,setPropertyValue的具体实现是在BeanWrapperImpl类中,这里是有点烦。我们具体看该方法:
代码1.7:BeanWrapperImpl类的setPropertyValue方法
public void setPropertyValue(PropertyValue pv) throws BeansException { PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens; if (tokens == null) {//如果tokens为空 String propertyName = pv.getName(); BeanWrapperImpl nestedBw; try { nestedBw = getBeanWrapperForPropertyPath(propertyName); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Nested property in path '" + propertyName + "' does not exist", ex); } tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); if (nestedBw == this) { pv.getOriginalPropertyValue().resolvedTokens = tokens; } nestedBw.setPropertyValue(tokens, pv); } else {//不为空直接开始注入 setPropertyValue(tokens, pv); } }这个方法很关键,不过《Spring技术内幕》和网上的闲杂资料都没有讲解该方法的,我相信90%以上的同学会看不懂这个方法。我在网上看了很多资料,大概知道几个重要方法的作用,这里简单说下:
getBeanWrapperForPropertyPath:通过嵌套属性的路径递归得到一个BeanWrapperImpl实例
protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); // Handle nested properties recursively. if (pos > -1) { String nestedProperty = propertyPath.substring(0, pos); String nestedPath = propertyPath.substring(pos + 1); BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty); return nestedBw.getBeanWrapperForPropertyPath(nestedPath); } else { return this; } }这段代码的作用就是:比如我们传过来的propertyPath是beanA.beanB,那么这里得到的就是beanB的BeanWrapperImpl实例。
getPropertyNameTokens:解析指定的属性名称,并赋值到对应的属性标示中(PropertyTokenHolder)
private PropertyTokenHolder getPropertyNameTokens(String propertyName) { PropertyTokenHolder tokens = new PropertyTokenHolder(); String actualName = null; List<String> keys = new ArrayList<String>(2); int searchIndex = 0; while (searchIndex != -1) { int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex); searchIndex = -1; if (keyStart != -1) { int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length()); if (keyEnd != -1) { if (actualName == null) { actualName = propertyName.substring(0, keyStart); } String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd); if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { key = key.substring(1, key.length() - 1); } keys.add(key); searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length(); } } } tokens.actualName = (actualName != null ? actualName : propertyName); tokens.canonicalName = tokens.actualName; if (!keys.isEmpty()) { tokens.canonicalName += PROPERTY_KEY_PREFIX + StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) + PROPERTY_KEY_SUFFIX; tokens.keys = StringUtils.toStringArray(keys); } return tokens; }这段代码可以举个例子:比如输入 infoList[2],那么tokens.actualName=infoList,tokens.canonicalName=infoList[2],tokens.keys=["2"];
所以:我纳闷的是,我们在对Property属性注入的时候,哪来的这样类型的数据。而且这个tokens是用来判断属性是集合类型还是其他类型的根据,真的想不通!希望得到大家的指点! 【add 20160805】--今天debug了一天,就是想找找怎样配置才能弄出这样的数据,后来发现我们项目中即使是如下的配置:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!--dataSource属性指定要用到的数据源,因此在Hibernate的核心配置文件中就无需再配置与数据库连接相关的属性--> <property name="dataSource" ref="builderDataSource" /> <property name="hibernateProperties"> <props> <!-- Hibernate基本配置 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.connection.pool_size">10</prop> <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 结果集滚动 --> <prop key="jdbc.use_scrollable_resultset">false</prop> </props> </property> <!-- 加入使用注解的实体类,用扫描的方式--> <property name="packagesToScan"> <list> <value>com.gh.codebuilder.entity.*</value> </list> </property> </bean>得到的tokens也是null,也就是说依然是用jdk反射调用setter方法处理的。所以这里应该不是针对bean在配置的使用,有可能像我们在JSP提交form的时候
user.name,user.ids[0]之类的这个时候才用得到。【待验证】
OK,言归正传,真正的属性解析还在setPropertyValue方法中,我们先跳过这里去看下源码【该方法很长】:
代码1.:8:BeanWrapperImpl类的setPropertyValue方法:
@SuppressWarnings("unchecked") private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; //keys是用来保存集合类型属性的size if (tokens.keys != null) { //将属性信息拷贝 PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue; try { //获取属性值,该方法内部使用JDK的内省( Introspector)机制,调用属性的getter(readerMethod)方法,获取属性的值 propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } //获取集合类型属性的长度 String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } //注入array类型的属性值 else if (propValue.getClass().isArray()) { //获取属性的描述符 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); //获取数组的类型 Class requiredType = propValue.getClass().getComponentType(); //获取数组的长度 int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { //获取数组以前初始化的值 if (isExtractOldValueForEditor()) { oldValue = Array.get(propValue, arrayIndex); } //将属性的值赋值给数组中的元素 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType)); Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } //注入list类型的属性值 else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); //获取list集合的类型 Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType( pd.getReadMethod(), tokens.keys.length); List list = (List) propValue; //获取list集合的size int index = Integer.parseInt(key); Object oldValue = null; if (isExtractOldValueForEditor() && index < list.size()) { oldValue = list.get(index); } //获取list解析后的属性值 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType)); if (index < list.size()) { //为list属性赋值 list.set(index, convertedValue); } else if (index >= list.size()) {//如果list的长度大于属性值的长度,则多余的元素赋值为null for (int i = list.size(); i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + list.size() + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } } //注入map类型的属性值 else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( pd.getReadMethod(), tokens.keys.length); Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( pd.getReadMethod(), tokens.keys.length); Map map = (Map) propValue; Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType)); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } Object convertedMapValue = convertIfNecessary( propertyName, oldValue, pv.getValue(), mapValueType, new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1))); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); } } else {//对非集合类型的属性注入 PropertyDescriptor pd = pv.resolvedDescriptor; if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); //无法获取到属性名或者属性没有提供setter(写方法)方法 if (pd == null || pd.getWriteMethod() == null) { //如果属性值是可选的,即不是必须的,则忽略该属性值 if (pv.isOptional()) { logger.debug("Ignoring optional value for property '" + actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); return; } else {//如果属性值是必须的,则抛出无法给属性赋值,因为没提供setter方法异常 PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException( getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } } pv.getOriginalPropertyValue().resolvedDescriptor = pd; } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.conversionNecessary)) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { //获取属性的getter方法(读方法),JDK内省机制 final Method readMethod = pd.getReadMethod(); //如果属性的getter方法不是public访问控制权限的,即访问控制权限比较严格,则使用JDK的反射机制强行访问非public的方法(暴力读取属性值) if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager()!= null) { //匿名内部类,根据权限修改属性的读取控制限制 AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } try { //调用读取属性值的方法,获取属性值 if (System.getSecurityManager() != null) { oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return readMethod.invoke(object); } }, acc); } else { oldValue = readMethod.invoke(object); } } catch (Exception ex) { if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName + "'", ex); } } } //设置属性的注入值 valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd); } pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue); } //根据JDK的内省机制,获取属性的setter(写方法)方法 final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : pd.getWriteMethod()); //如果属性的setter方法是非public,即访问控制权限比较严格,则使用JDK的反射机制,强行设置setter方法可访问(暴力为属性赋值) if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager()!= null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(this.object, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } }关于这个方法,大家不要慌,我们从以下几点来看:
根据tokens是否为空分为:集合类型和非集合类型。
集合类型的注入:一般都是这么个规律:根据key先去getter旧值,再取得已经转换好的真正的实例值,setter到指定的位置。也就是书上说的:将其属性值解析为目标类型的集合后直接赋值给属性
非集合类型:大量使用了JDK的反射和内省机制,通过属性的getter方法(reader method)获取指定属性注入以前的值,同时调用属性的setter方法(writer method)为属性设置注入后的值。
到这里依赖注入就完事了,跟其他博主不一样,看到这里我相信大家都晕了吧。我在本篇博客上也抛出了问题。后面我应该还会再来一篇文章进行补充的,主要针对上面那个问题和对代码流程的总结。
相关文章推荐
- Spring IOC/BeanFactory/ApplicationContext的工作流程/实现原理/初始化/依赖注入源码详解
- Spring应用、原理以及粗读源码系列(一)--框架总述、以Bean为核心的机制(IoC容器初始化以及依赖注入)
- 8-spring源码3.2.18解读+spring技术内幕(IOC容器的依赖注入(反射+递归调用))
- Spring:源码解读(IOC容器的依赖注入)
- Ioc容器依赖注入-Spring 源码(2)
- 【Spring源码--IOC容器的实现】(五)Bean对象的创建
- Spring源码学习之:模拟实现BeanFactory,从而说明IOC容器的大致原理
- Spring源码阅读(三)—IOC容器依赖注入
- Spring IOC源码详解之容器依赖注入
- 使用XPath解析xml实现简单的Spring IOC完成bean的依赖注入
- Spring源码-IOC容器(六)-bean的循环依赖
- Ioc容器依赖注入-Spring 源码系列(2)
- Spring源码解析三:IOC容器的依赖注入
- Spring源码学习IOC(5):IOC容器的依赖注入
- spring技术内幕5-IoC容器的依赖注入
- SpringMVC 源代码深度解析 IOC容器(Bean实例化和依赖注入)
- Spring源码学习IOC(4):IoC容器解析Bean定义资源并注册解析后的Bean
- IoC 依赖注入、以及在Spring中的实现
- spring源码学习之路---IOC容器初始化要义之bean定义载入
- 【第十二章】零配置 之 12.1 概述 12.2 注解实现Bean依赖注入 ——跟我学spring3