Spring 源码系列-BeanWrapper

BeanWrapper 是 Spring 提供的一个用来操作javaBean 属性的工具,使用它可以直接修改一个对象的属性。

对于 bean 属性的操作,大家熟知的主要有下面这些工具类:

  • 1.Apache 的 BeanUtils 和 PropertyUtils
  • 2.cglib 的 BeanMap 和 BeanCopier
  • 3.spring 的 BeanUtils

Spring 中 BeanWrapper 的主要功能在于:

  • 1.支持设置嵌套属性
  • 2.支持属性值的类型转换(设置ConversionService)
  • 3.提供分析和操作标准JavaBean的操作:获取和设置属性值(单独或批量),获取属性描述符以及查询属性的可读性/可写性的能力。

BeanWrapper 本身是一个接口,它提供了一整套处理 Bean 的方法。源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface BeanWrapper extends ConfigurablePropertyAccessor {
//为数组和集合自动增长指定一个限制。在普通的BeanWrapper上默认是无限的。
void setAutoGrowCollectionLimit(int autoGrowCollectionLimit);
//返回数组和集合自动增长的限制。
int getAutoGrowCollectionLimit();
//如果有的话,返回由此对象包装的bean实例
Object getWrappedInstance();
//返回被包装的JavaBean对象的类型。
Class<?> getWrappedClass();
//获取包装对象的PropertyDescriptors(由标准JavaBeans自省确定)。
PropertyDescriptor[] getPropertyDescriptors();
//获取包装对象的特定属性的属性描述符。
PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException;
}

上面的 BeanWrapper 是基于4.3.6 版本的,这个接口在 4.1 版本之后略有改动。BeanWrapperImpl 是 BeanWrapper 的实现类,BeanWrapperImpl 的父类是 AbstractNestablePropertyAccessor,通过这个使得 BeanWrapper 具有处理属性的能力。

下面是一个使用 BeanWrapper 包装对象的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.glmapper.spring.test;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.PropertyValue;
/**
* BeanWrapper 测试类
*/
public class BeanWrapperTest {
public static void main(String[] args) {
User user=new User();
//通过PropertyAccessorFactory将user对象封装成BeanWrapper
BeanWrapper bw=PropertyAccessorFactory.forBeanPropertyAccess(user);
//方式一:直接对属性值进行设置
bw.setPropertyValue("userName", "张三");
//方式二:通过PropertyValue进行设置
PropertyValue pv=new PropertyValue("userName","李四");
bw.setPropertyValue(pv);


System.out.println(user.getUserName());
}
}
//一个User类
class User{
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

在 Spring 中,有很多 Bean 属性的操作都是通过 BeanWrapper 来完成的,比如常见的 HttpServletBean 的属性设置就是。

注:本文摘自我的博客园文章,进行了一些包装,放在Spring源码系列中。
Spring中的 BeanWrapper

作者

卫恒

发布于

2018-02-07

更新于

2022-04-24

许可协议

评论