环境:JDK7,tomcat7
问题:bean对象使用了@Accessors(chain = true) 注解,
-
在调用BeanUtils.setProperty(t, field.getName(), objvalue);
-
由于链式调用重写了 set方法返回值为对象this,导致BeanUtils调用反射获取set方法时获取不到,最终没有对需要值的对象set进入值
-
但是实际测试和本地环境可以获取到值,而生产环境获取不到
网上找到拿不到值的原因
cglib中使用 Java rt.jar包中的java.beans.Introspector类,在java.beans.Introspector类520行:只获取返回值是void类型的setxxxx方法,而@Accessors(chain=true)下setter方法返回当前对象,这个显然会有问题。
if (argCount == 0) {
if (name.startsWith(GET_PREFIX)) {
// Simple getter
pd = new PropertyDescriptor(this.beanClass, name.substring(3), method, null);
} else if (resultType == boolean.class && name.startsWith(IS_PREFIX)) {
// Boolean getter
pd = new PropertyDescriptor(this.beanClass, name.substring(2), method, null);
}
} else if (argCount == 1) {
if (int.class.equals(argTypes[0]) && name.startsWith(GET_PREFIX)) {
pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, method, null);
// 核心问题在这里如果set方法返回不是void则不把set方法放到当前类的
// private HashMap pdStore = new HashMap();中
} else if (void.class.equals(resultType) && name.startsWith(SET_PREFIX)) {
// Simple setter
pd = new PropertyDescriptor(this.beanClass, name.substring(3), null, method);
if (throwsException(method, PropertyVetoException.class)) {
pd.setConstrained(true);
}
}
} else if (argCount == 2) {
if (void.class.equals(resultType) && int.class.equals(argTypes[0]) && name.startsWith(SET_PREFIX)) {
pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, null, method);
if (throwsException(method, PropertyVetoException.class)) {
pd.setConstrained(true);
}
}
}
这段代码结束后调用下一个方法processPropertyDescriptors
查看DefaultBeanIntrospector类的核心生产beanInfo
public void introspect(final IntrospectionContext icontext) {
BeanInfo beanInfo = null;
try {
// 这里通过上述类Introspector 获取bean,按照上面说法此时如果set方法返回的不是Null 依然还拿不到方法
beanInfo = Introspector.getBeanInfo(icontext.getTargetClass());
} catch (final IntrospectionException e) {
// no descriptors are added to the context
log.error(
"Error when inspecting class " + icontext.getTargetClass(),
e);
return;
}
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
if (descriptors == null) {
descriptors = new PropertyDescriptor[0];
}
handleIndexedPropertyDescriptors(icontext.getTargetClass(),
descriptors);
icontext.addPropertyDescriptors(descriptors);
}
整个方法走完此时icontext中添加的descriptors 对象属性值writeMethodName 依然是null
实际上apache除了默认提供的DefaultBeanIntrospector 使用jdk的内省Introspector
还提供了FluentPropertyBeanIntrospector 和SuppressPropertiesBeanIntrospector
其中FluentPropertyBeanIntrospector 可以解决上述问题
其方法introspect() 会只根据方法名进行映射 反射Method类
而SuppressPropertiesBeanIntrospector 是抑制内省 ,观察其introspect() 方法,
会在实际过程中 过滤 构造SuppressPropertiesBeanIntrospector时 , 传入的final Collection<String> propertiesToSuppress,集合进行方法过滤remove
当然也可以根据实际业务需求 继续BeanIntrospector 编写自定义的 内省过滤器
我们项目中后续使用了BeanConverter 直接 生成set get方法的实体类。