首先定義UtilDatePropertyEdit類繼承自PropertyEditorSupport
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 自定義屬性編輯器
* @author yqs
*
*/
public
class UtilDatePropertyEdit
extends PropertyEditorSupport {
private String format =
"yyyy/MM/dd";
public
void setAsText(String text)
throws IllegalArgumentException {
System.out.println(text +
"----");
SimpleDateFormat sdf =
new SimpleDateFormat(format);
try {
Date d = sdf.parse(text);
this.setValue(d);
}
catch (ParseException e) {
e.printStackTrace();
}
}
public
void setFormat(String format) {
this.format = format;
}
}
而後在applicationContext-editor.xml配置文件裏對編輯器進行定義,代碼以下
<!--
定義屬性編輯器 -->
<
bean
id
="customEditorConfigurer"
class
="org.springframework.beans.factory.config.CustomEditorConfigurer"
>
<
property
name
="customEditors"
>
<
map
>
<
entry
key
="java.util.Date"
>
<
bean
class
="com.yqs.spring.UtilDatePropertyEdit"
>
<
property
name
="format"
value
="yyyy-MM-dd"
/>
</
bean
>
</
entry
>
</
map
>
</
property
>
</
bean
>
在配置文件裏配置一下就能夠使用了
<
property
name
="dateValue"
>
<
value
>2008-11-25
</
value
>
</
property
>
如下是使用方法,包括int、String、list、set、map、arrays等的用法
public
class InjectionTest
extends TestCase {
private BeanFactory factory;
protected
void setUp()
throws Exception {
factory =
new ClassPathXmlApplicationContext(
"applicationContext-*.xml");
}
public
void testInjection() {
Bean1 bean1 = (Bean1)factory.getBean(
"bean1");
System.out.println(bean1.getStrValue());
System.out.println(bean1.getIntValue());
//System.out.println(bean1.getListValue());
List<String> list = bean1.getListValue();
for(String element : list) {
//Enhanced for loop need Generic
System.out.println(element);
}
Set<String> set = bean1.getSetValue();
for(String str : set) {
System.out.println(str);
}
Map map = bean1.getMapValue();
Collection<String> coll = map.values();
for(String str : coll) {
System.out.println(str);
}
String[] strs = bean1.getArrayValue();
for(String str : strs) { System.out.println(str); } Date d = bean1.getDateValue(); System.out.println(d); Date d2 = bean1.getDateValue2(); System.out.println(d2); } }