用于属性的转换,是BeanPostProcessor的一种,比如有如下两个java类:
假若在XML中进行如下配置:
这时候在getBean("person")的时候是有问题的。通过PropertyEditor 可以将字符串映射为其它类型:
在XML中注册一下该转换器:
这时候便可正确的注入了:
01 | package com.google.spring.applicationContext; |
02 |
03 | public class Computer |
04 | { |
05 | private String name; |
06 | |
07 | public Computer() |
08 | { |
09 | |
10 | } |
11 | |
12 | public Computer(String name) |
13 | { |
14 | this .name = name; |
15 | } |
16 |
17 | public String getName() |
18 | { |
19 | return name; |
20 | } |
21 |
22 | public void setName(String name) |
23 | { |
24 | this .name = name; |
25 | } |
26 | |
27 | } |
01 | package com.google.spring.applicationContext; |
02 |
03 | public class Person |
04 | { |
05 | private Computer computer ; |
06 |
07 | public Computer getComputer() |
08 | { |
09 | return computer; |
10 | } |
11 |
12 | public void setComputer(Computer computer) |
13 | { |
14 | this .computer = computer; |
15 | } |
16 | |
17 | |
18 | } |
1 | < bean id = "person" class = "com.google.spring.applicationContext.Person" > |
2 | < property name = "computer" > |
3 | < value >lenovo</ value > |
4 | </ property > |
5 | </ bean > |
01 | package com.google.spring.applicationContext; |
02 |
03 | import java.beans.PropertyEditorSupport; |
04 |
05 | public class ComputerTypeEditor extends PropertyEditorSupport |
06 | { |
07 | private String format; |
08 |
09 | public String getFormat() |
10 | { |
11 | return format; |
12 | } |
13 |
14 | public void setFormat(String format) |
15 | { |
16 | this .format = format; |
17 | } |
18 | |
19 | public void setAsText(String text) |
20 | { |
21 | Computer computer = new Computer(text); |
22 | this .setValue(computer); |
23 | } |
24 | } |
01 | < bean id = "customEditorConfigure" class = "org.springframework.beans.factory.config.CustomEditorConfigurer" > |
02 | < property name = "customEditors" > |
03 | < map > |
04 | < entry key = "com.google.spring.applicationContext.Computer" > |
05 | < bean class = "com.google.spring.applicationContext.ComputerTypeEditor" > |
06 | < property name = "format" > |
07 | < value >upperCase</ value > |
08 | </ property > |
09 | </ bean > |
10 | </ entry > |
11 | </ map > |
12 | </ property > |
13 | </ bean > |
1 | Person person = (Person)applicationContext.getBean( "person" ); |