您的位置:首页 > 编程语言 > Java开发

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

2013-01-30 11:23 387 查看
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) {
[color=green]Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));[/color]
}
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐