首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

Spring 标注@Autowired 如若做到自动装配私有变量而不使用set方法的原理

2013-02-06 
Spring 标注@Autowired 如果做到自动装配私有变量而不使用set方法的原理Spring 标注@Autowired 如果做到自

Spring 标注@Autowired 如果做到自动装配私有变量而不使用set方法的原理
Spring 标注@Autowired 如果做到自动装配私有变量而不使用set方法的原理

熟悉jdk的话就知道,方法就是使用java.lang.reflect.Field类的:Field.setAccessible(true); 将字段设置为‘true’,就可以直接使用set方法为其赋值了。

如果不设置‘true’的话,则会抛出‘java.lang.IllegalAccessException’的异常

Spring中的代码如下(标绿的部分):
------------------------------------------

          /**
          * Either this or {@link #getResourceToInject} needs to be overridden.
          */
          protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable {
               if (this.isField) {
                    Field field = (Field) this.member;
                    ReflectionUtils.makeAccessible(field);
                    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();
                    }
               }
          }


热点排行