Spring提供了一个BeanFactoryPostProcessor接口的实现类:CustomEditorConfigurer。这个类可以实现java.beans.PropertyEditor接口的类,并将字符串值转换为指定类型的对象。
通过一个简单的例子来说明。
导入Spring所需的包:commons-logging.jar,spring.jar 。(日志包和Spring包)
包下载地址: http://www.blogjava.net/Files/ducklyl/Spring.rar
undefined
undefined
(
1
)创建User 类
package com.editor;
public
class
User {
private
String name;
private
int
number;
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name
=
name;
}
public
int
getNumber() {
return
number;
}
public
void
setNumber(
int
number) {
this
.number
=
number;
}
}
(
2
)创建HelloBean 类
package com.editor;
public
class
HelloBean {
private
String helloWord;
private
User user;
public
String getHelloWord() {
return
helloWord;
}
public
void
setHelloWord(String helloWord) {
this
.helloWord
=
helloWord;
}
public
User getUser() {
return
user;
}
public
void
setUser(User user) {
this
.user
=
user;
}
}
(
3
)创建UserEditor 类
package com.editor;
import java.beans.PropertyEditorSupport;
public
class
UserEditor extends PropertyEditorSupport{
public
void
setAsText(String text)
{
String[] strs
=
text.split(
"
,
"
);
int
number
=
Integer.parseInt(strs[
1
]);
User user
=
new
User();
user.setName(strs[
0
]);
user.setNumber(number);
setValue(user);
}
}
(
4
)在类路径下创建property
-
config.xml
<?
xml version
=
"
1.0
"
encoding
=
"
UTF-8
"
?>
<!
DOCTYPE beans PUBLIC
"
-//SPRING//DTD BEAN//EN
"
"
http://www.springframework.org/dtd/spring-beans.dtd
"
>
<
beans
>
<
bean id
=
"
EditorConfigBean
"
class
=
"
org.springframework.beans.factory.config.CustomEditorConfigurer
"
>
<
property name
=
"
customEditors
"
><!--
CustomEditorConfigurer类会加载
"
customEditors
"
属性设定的map
-->
<
map
>
<
entry key
=
"
com.editor.User
"
>
<
bean id
=
"
userEditor
"
class
=
"
com.editor.UserEditor
"
/>
</
entry
>
</
map
>
</
property
>
</
bean
>
<
bean id
=
"
helloBean
"
class
=
"
com.editor.HelloBean
"
>
<
property name
=
"
helloWord
"
>
<
value
>
Hello
!</
value
>
</
property
>
<
property name
=
"
user
"
>
<
value
>
ducklyl,
123456
</
value
>
</
property
>
</
bean
>
</
beans
>
(
5
)创建测试类
package com.editor;
import org.springframework.context.
*
;
import org.springframework.context.support.
*
;
public
class
SpirngTest {
public
static
void
main(String[] args)
{
//
读取配置文件
ApplicationContext context
=
new
FileSystemXmlApplicationContext(
"
property-config.xml
"
);
//
获取id="helloBean"对象
HelloBean hello
=
(HelloBean)context.getBean(
"
helloBean
"
);
//
调用helloBean对象getHelloWord()方法
System.
out
.println(hello.getHelloWord());
System.
out
.println(
"
Name:
"
+
hello.getUser().getName());
System.
out
.println(
"
Number:
"
+
hello.getUser().getNumber());
}
}
如果以上正确设置,运行结果为:
Hello
!
Name:ducklyl
Number:
123456
原文地址