Spring攻略学习笔记 ------创建自定义属性编辑器

2014-11-24 02:42:07 · 作者: · 浏览: 1

、知识点


通过实现java.beans.PropertyEditor接口或者继承便利的支持类 java.beans.PropertyEditorSupport,可以编写自定义的属性编辑器。

二、代码示例

Product类的属性编辑器


[java] package com.codeproject.jackie.springrecipesnote.springadvancedioc;

import java.beans.PropertyEditorSupport;

/**
* Product类的属性编辑器
* @author jackie
*
*/
public class ProductEditor extends PropertyEditorSupport {

/**
* 将属性转换成字符串值
*/
public String getAsText() {
Product product = (Product) getValue();
return product.getClass().getName() + "," + product.getName() + "," + product.getPrice();
}

/**
* 将字符串转换成属性
*/
public void setAsText(String text) throws IllegalArgumentException {
String[] parts = text.split(",");
try {
Product product = (Product) Class.forName(parts[0]).newInstance();
product.setName(parts[1]);
product.setPrice(Double.parseDouble(parts[2]));
setValue(product);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}

package com.codeproject.jackie.springrecipesnote.springadvancedioc;

import java.beans.PropertyEditorSupport;

/**
* Product类的属性编辑器
* @author jackie
*
*/
public class ProductEditor extends PropertyEditorSupport {

/**
* 将属性转换成字符串值
*/
public String getAsText() {
Product product = (Product) getValue();
return product.getClass().getName() + "," + product.getName() + "," + product.getPrice();
}

/**
* 将字符串转换成属性
*/
public void setAsText(String text) throws IllegalArgumentException {
String[] parts = text.split(",");
try {
Product product = (Product) Class.forName(parts[0]).newInstance();
product.setName(parts[1]);
product.setPrice(Double.parseDouble(parts[2]));
setValue(product);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}

实际上,JavaBeans API将自动搜索类的属性编辑器。为了能搜索到正确的属性编辑器,它必须位于目标类的相同包里,名称必须是目标类名加上Editor后缀。如果你自定义的属性编辑器遵照这种约定,就像ProductEditor,那么就没有必要再Spring IoC容器中再次注册。否则的话,必须要在CustomEditorConfigurer实例中注册自定义编辑器,才能使用它。注册方法与内置编辑器相同。

[java] < xml version="1.0" encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">





















com.codeproject.jackie.springrecipesnote.springadvancedioc.Disc,CD-RW,1.5




< xml version="1.0" encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">





















com.codeproject.jackie.springrecipesnote.springadvancedioc.Disc,CD-RW,1.5