(spring-第13回【IoC基础篇】)PropertyEditor(属性编辑器)--实例化Bean的第五大利器

上一篇讲到JavaBeans的属性编辑器,编写自己的属性编辑器,需要继承PropertyEditorSupport,编写自己的BeanInfo,需要继承SimpleBeanInfo,然后在BeanInfo中把特定的属性编辑器和需要编辑的属性绑定起来(详情请查看上一篇)。

Spring的属性编辑器仅负责将配置文件中的字面值转换成Bean属性的对应值。(而JavaBean的属性编辑器能够通过界面来手动设置bean属性的值)。如果属性的类型不同,转换的方法就不同。正如javabean的属性编辑器一样,特定类型的属性对应着特定的属性编辑器。Spring在PropertyEditorSupport中提供了默认的属性编辑器。PropertyEditorSupport中有两个重要的变量:defaultEditors、customEditors,它们分别存放默认的属性编辑器和用户自定义的属性编辑器。 下面是PropertyEditorSupport的部分源码:

 private void createDefaultEditors() {
this.defaultEditors = new HashMap<Class, PropertyEditor>(64); // Simple editors, without parameterization capabilities.
// The JDK does not contain a default editor for any of these target types.
this.defaultEditors.put(Charset.class, new CharsetEditor());
this.defaultEditors.put(Class.class, new ClassEditor());
this.defaultEditors.put(Class[].class, new ClassArrayEditor());
this.defaultEditors.put(Currency.class, new CurrencyEditor());
this.defaultEditors.put(File.class, new FileEditor());
this.defaultEditors.put(InputStream.class, new InputStreamEditor());
this.defaultEditors.put(InputSource.class, new InputSourceEditor());
this.defaultEditors.put(Locale.class, new LocaleEditor());
this.defaultEditors.put(Pattern.class, new PatternEditor());
this.defaultEditors.put(Properties.class, new PropertiesEditor());
this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor());
this.defaultEditors.put(TimeZone.class, new TimeZoneEditor());
this.defaultEditors.put(URI.class, new URIEditor());
this.defaultEditors.put(URL.class, new URLEditor());
this.defaultEditors.put(UUID.class, new UUIDEditor()); // Default instances of collection editors.
// Can be overridden by registering custom instances of those as custom editors.
this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class));
this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class));
this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class));
this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class));
this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class)); // Default editors for primitive arrays.
this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor());
this.defaultEditors.put(char[].class, new CharArrayPropertyEditor()); // The JDK does not contain a default editor for char!
this.defaultEditors.put(char.class, new CharacterEditor(false));
this.defaultEditors.put(Character.class, new CharacterEditor(true)); // Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor.
this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false));
this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true)); // The JDK does not contain default editors for number wrapper types!
// Override JDK primitive number editors with our own CustomNumberEditor.
this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false));
this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true));
this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false));
this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true));
this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false));
this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true));
this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false));
this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true));
this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false));
this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true));
this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false));
this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true));
this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true)); // Only register config value editors if explicitly requested.
if (this.configValueEditorsActive) {
StringArrayPropertyEditor sae = new StringArrayPropertyEditor();
this.defaultEditors.put(String[].class, sae);
this.defaultEditors.put(short[].class, sae);
this.defaultEditors.put(int[].class, sae);
this.defaultEditors.put(long[].class, sae);
}
}

可以看到,defaultEditors、customEditors是哈希Map类型的,以属性的类为键,以对应属性编辑器的对象为值。

以48行为例,我们看一下CustomNumberEditor是个什么鬼,下面是源码:

 public class CustomNumberEditor extends PropertyEditorSupport {

     private final Class numberClass;

     private final NumberFormat numberFormat;

     private final boolean allowEmpty;

     public CustomNumberEditor(Class numberClass, boolean allowEmpty) throws IllegalArgumentException {
this(numberClass, null, allowEmpty);
} public CustomNumberEditor(Class numberClass, NumberFormat numberFormat, boolean allowEmpty)
throws IllegalArgumentException { if (numberClass == null || !Number.class.isAssignableFrom(numberClass)) {
throw new IllegalArgumentException("Property class must be a subclass of Number");
}
this.numberClass = numberClass;
this.numberFormat = numberFormat;
this.allowEmpty = allowEmpty;
} /**
* Parse the Number from the given text, using the specified NumberFormat.
*/
@Override
@SuppressWarnings("unchecked")
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
}
else if (this.numberFormat != null) {
// Use given NumberFormat for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
}
else {
// Use default valueOf methods for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass));
}
} /**
* Coerce a Number value into the required target class, if necessary.
*/
@Override
@SuppressWarnings("unchecked")
public void setValue(Object value) {
if (value instanceof Number) {
super.setValue(NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass));
}
else {
super.setValue(value);
}
} /**
* Format the Number as String, using the specified NumberFormat.
*/
@Override
public String getAsText() {
Object value = getValue();
if (value == null) {
return "";
}
if (this.numberFormat != null) {
// Use NumberFormat for rendering value.
return this.numberFormat.format(value);
}
else {
// Use toString method for rendering value.
return value.toString();
}
} }

真相大白,与上一节javabean的属性编辑器类似,CustomNumberEditor 是spring内置的属性编辑器,它也是继承了PropertyEditorSupport ,并且覆盖了setAsText、setValue、getAsText方法。所以,这是扩展javabean的属性编辑器的通用方法。那么我们编写自己的属性编辑器也应该这样做。(javabean的属性编辑器相关内容请查看上一节)。而且结合上一节我们知道在这里,getAsText表示把<bean>标签里的属性值拿到,而setAsText表示把拿到的标签字面值转换成bean属性的有变量类型的值。比如,下面是Car的XML属性配置:

 <bean id="car" class="com.mesopotamia.test1.Car"
p:name="汽车"
p:brand="宝马"
p:maxSpeed="200"/>

下面是Car的Bean类:

 public class Car {
private String name;
private String brand;
private double maxSpeed;

在XML属性配置中是没有类型之分的,经过属性编辑器的转换,就可以给Car的对应属性赋予对应的值。

spring提供的默认属性编辑器支持的类型是有限的,如果要自定义属性编辑器,就要扩展PropertyEditorSupport ,并且把自己的属性编辑器注册到spring容器中。下面我们一起来设计一个自定义的属性编辑器并把它注册到spring容器中使用。

现在有一个Car类:

 public class Car {
private String name;
private String brand;
private double maxSpeed;
。。。
省略getter、setter方法 public String toString(){
return "名字:"+name+" 型号:"+brand+" 速度:"+maxSpeed;
}

有一个Store类,这个Store类拥有一个Car类型的属性:

 public class Store {

     private Car car;

 。。。省略getter、setter方法。

 public String toString(){
return car.toString();
}

下面是配置文件:

 <bean id="car" class="com.mesopotamia.test1.Car"
p:name="汽车"
p:brand="宝马"
p:maxSpeed=""/> <bean id="store" class="com.mesopotamia.test1.Store">
<property name="car">
<ref bean="car"/>
</property>
</bean>

这是典型的bean引用方式。那么,当我加载spring容器,调用Store类的对象,该Store的car属性就自动拥有了name、brand、maxSpeed值了。下面是Main:

 public static void main(String args[]){
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/mesopotamia/test1/*.xml");
//Car car1 = ctx.getBean("car1",Car.class);
Store store=ctx.getBean("store",Store.class);
log.info(store.toString());
}

运行结果:

 2015-11-29 23:21:24,446  INFO [main] (Car.java:22) - 调用了Car的构造函数,实例化了Car..
2015-11-29 23:21:24,493 INFO [main] (Store.java:13) - 调用了Store的构造函数,实例化了Store。。。
2015-11-29 23:21:24,505 INFO [main] (Main.java:16) - 名字:汽车 型号:宝马 速度:200.0

第1、2行的打印语句我分别写在Car、Store的构造函数里,所以,一经实例化必须打印。而第3行,我打印的是store 的toString()方法,而该方法又调用的是Car的toString()方法,然后打印出了Car的属性值。

完美。然而,我们现在不这样干,换个玩儿法,我把配置文件改为如下的方式:

  <bean id="car" class="com.mesopotamia.test1.Car"/>

    <bean id="store" class="com.mesopotamia.test1.Store">
<property name="car" value="汽车,宝马,200.00"/>
</bean>

规则变了,我要求在实例化Store后,把汽车,宝马,200.00分别赋值给Store的Car属性的对应变量。

而属性编辑器就是为了把这个字面值转换成具体属性的值的,因此,需要使用属性编辑器。

而本例中这种转换方式spring的默认属性编辑器并不支持,所以,我们要自定义属性编辑器。

自定义属性编辑器,首先,继承PropertyEditorSupport ,然后,覆盖setAsText()、getAsText()方法。

由于我们不需要跟javabean一样,用getAsText()获取属性值然后放到下拉框中,在当前属性编辑器中也不需要获取它,

所以,我们只需要覆盖setAsText()方法。代码如下:

 public class CustomCarEditor extends PropertyEditorSupport {
public void setAsText(String text){
if(text == null || text.indexOf(",") == -1){
throw new IllegalArgumentException("设置的字符串格式不正确");
}
String[] infos = text.split(",");
Car car = new Car();
car.setName(infos[0]);
car.setBrand(infos[1]);
car.setMaxSpeed(Double.parseDouble(infos[2]));
setValue(car);
}

取出文本值,分割逗号,新建Car对象,设置属性值,最后调用父类的setValue方法给Store的Car属性赋值。

那么setValue如何知道把括号里的对象参数赋予给谁呢?我们注册该属性编辑器时就会知道。

自定义的属性编辑器写好了,接下来要注册到spring容器中,注册方法如下:

  <bean id="store" class="com.mesopotamia.test1.Store">
<property name="car" value="汽车,宝马,200.00"/>
</bean> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.mesopotamia.test1.Car">
<bean class="com.mesopotamia.test1.CustomCarEditor" />
</entry>
</map>
</property>
</bean>

实际上是注册加载了CustomEditorConfigurer,这个类是专门负责注册自定义属性编辑器的。我们一开始讲到,PropertyEditorSupport里面有个变量叫customEditors,用来存放自定义属性编辑器,它是一个HashMap类型,其中Key是属性类,Value是属性对应的属性编辑器。而上面配置文件中的6-9行恰好是customEditors变量以及存放的map。CustomEditorConfigurer就负责把6-9行转换成哈希Map交给PropertyEditorSupport。

当BeanWrapper在设置store的car属性时(BeanWrapper负责在实例化后期设置属性值),它会检索自定义属性编辑器的注册表,然后发现Car属性类型对应着CustomCarEditor,它就会去寻找这个属性编辑器进行后续操作。

自定义属性编辑器步骤总结:

  1. 继承PropertyEditorSupport类,覆盖setAsText方法;
  2. 注册自定义的属性编辑器。

CustomEditorConfigurer是BeanFactoryPostProcessor的实现类,因此它也是一个工厂后处理器。所谓的工厂后处理器,就是在实例化bean的过程中对bean进行处理,工厂模式本身就是把用户要使用的bean在内部实例化好了,当外部调用的时候直接吐出一个现成的对象来,所以,属性编辑属于工厂后处理器的任务。

上一篇:hihoCoder hiho一下 第四十八周 题目1 : 拓扑排序·二


下一篇:第一章:大数据 の Linux 基础 [更新中]