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();
                    }
               }
          }


你可能感兴趣的:(@Autowired)