Spring中的PropertyEditor的简单实用方法
2012-08-06 23:09
218 查看
用于属性的转换,是BeanPostProcessor的一种,比如有如下两个java类:
假若在XML中进行如下配置:
这时候在getBean("person")的时候是有问题的。通过PropertyEditor 可以将字符串映射为其它类型:
在XML中注册一下该转换器:
view sourceprint?
这时候便可正确的注入了:
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 | } |
view sourceprint?
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" ); |
相关文章推荐
- Spring中的PropertyEditor的简单实用方法
- 防止浏览器记住用户名及密码的简单实用方法
- postgre 存储过程简单实用方法 (过程语言: PL/pgSQL)
- 从头认识Spring-3.2 简单的AOP日志实现-需要记录方法的运行时间
- 数据绑定应该算是Spring MVC的特点之一吧~简单易用且功能强大,极大地简化了我们编程人员对于用户输入数据的接收及转换。 早先版本的Spring中的数据绑定完全都是基于PropertyEditor
- WPF简单实用方法(持续更新)
- XStream的简单实用方法
- 简单记录spring在控制台向页面传參的几种方法
- Spring依赖翻转以及注入方法简单介绍
- 编辑受密码保护的word文档最简单实用的方法
- MemCache简单实用方法
- iOS简单实用方法封装
- 简单实用的两种MySQL数据库备份的方法
- 防止浏览器记住用户名及密码的简单实用方法
- win7下创建和删除服务的简单实用方法
- 指针指针--shared_ptr简单实用方法
- 实用知识:摇一摇功能的方法使用(真简单??)
- 【健康】下蹲5分钟,等于步行1小时!最简单实用的锻炼方法
- 将Access数据库导入到SQLite最简单最实用的方法 -转
- 将Access数据库导入到SQLite最简单最实用的方法