pring 中 通过 CustomeEditorConfigureer 实现类型转换的一点疑问!

在spring中可以通过CustomeEditorConfigurer自动去检测bean包所需要转换属性,自定义一个继承于 PropertyEditorSupport的 Editor类,通过配置文件注入到 CustomeEditoConfigurer类中,当该属性在容器中的值是字符串时,他就会调用setTextAs(String text),把字符串值转换成目标类型的实例。如果不能正转换,则抛出相应的异常...例子如下
Person.java

package com.demo11;

public class Person {

private String name;
private String sex;
private int age;


public Person(String name, int age, String sex){
this.name = name;
this.age= age;
this.sex = sex;
}

public String getSex(){
return sex;
}



public void setSex(String sex) {
this.sex = sex;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}



Company.java 其中包含 Person属性.


package com.demo11;

public class Company {
private Person director;

public Person getDirector() {
return director;
}

public void setDirector(Person director) {
this.director = director;
}

}




PersonEditor.java //继承自PropertyEditorSupport

package com.demo11;

import java.beans.PropertyEditorSupport;

public class PersonEditor extends PropertyEditorSupport {

@Override

public void setAsText(String text) throws IllegalArgumentException {

String[] tmp =text.split("-");

String name = tmp[0];

int age = Integer.parseInt(tmp[1]);

String sex = tmp[2];

Person person = new Person(name, age, sex);

setValue(person);

}

}




对应的配置文件:



<bean id="customEditorConfigurer"

class="org.springframework.beans.factory.config.CustomEditorConfigurer">

<property name="customEditors">

<map>

<entry key="com.demo11.Person">

<bean class="com.demo11.PersonEditor"></bean>

</entry>

</map>

</property>

</bean>

<bean id="company" class="com.demo11.Company">

<property name="director">

<value>nono-35-女</value>

</property>

</bean>


在测试类中


ApplicationContext act = new ClassPathXmlApplicationContext("com/demo11/bean.xml");

Company company = (Company)act.getBean("company");

System.out.println(company.getDirector().getName());


输出结果为 nono


[color=red][size=medium]这的确是很好的编程思想,但是这在实际应用中有啥好处,或者有哪些实用场合 ?目前为止我还孤陋寡闻,尚不知结果,希望看到的朋友能给我指教指教![/size][size=large][/size]![/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值