Spring自定义属性编辑器

     自定义属性编辑器必须继承 PropertyEditorSupport 类,实现其中的setAsText()方法,将字面值转换为属性类型的对象,再调用setValue()方法,设置转置后的属性对象。


public class CustomCarEditor extends PropertyEditorSupport{
 @Override
 public void setAsText(String text) throws IllegalArgumentException {
  System.out.println("调用setAsText()方法");
  if(text==null || text.indexOf(",")==-1){
   throw new IllegalArgumentException();
  }
  String[] infos = text.split(",");
  Car car = new Car();
  car.setBrand(infos[0]);
  car.setMaxSpeed(Integer.parseInt(infos[1]));
  car.setPrice(Double.parseDouble(infos[2]));
  //调用父类的setValue方法设置转换后的属性对象
  setValue(car);
 }

 

 <!-- 配置属性编辑器 -->
 <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
   <map>
   <!-- 定义一个属性编辑器 -->
    <entry>
        <!-- 属性编辑器对应的属性类型 -->
     <key><value>com.Spring.PropertyEditor.Car</value> </key>
     <!-- 对应的属性编辑器Bean -->
     <bean class="com.Spring.PropertyEditor.CustomCarEditor"></bean>
    </entry>
   </map>
  </property>
 </bean>
  
    <bean id="boss" class="com.Spring.PropertyEditor.Boss">
     <property name="name" value="John"></property>
     <!-- 使用上面的属性编辑器完成属性填充操作 -->
     <property name="car" value="宝马,200,200000"></property>
    </bean>
</beans>

public class PropertyEditor {
 public static void main(String[] args) {
  ApplicationContext cxt = new ClassPathXmlApplicationContext       ("com/Spring/PropertyEditor/bean.xml");
  Boss boss = (Boss)cxt.getBean("boss");
  boss.say();
 }
}

    CustomEditorConfigurer是实现了BeanFactoryPostProcessor接口的类,因此是一个Bean工厂后处理器,所以在容器启动后有机会注入自定义的属性编辑器。

    自定义属性编辑器不常用,一般可以通过引用即<ref>其他的Bean即可,但是有时候比较复杂的情况下,会需要将属性对象一步步肢解为最终可用基本类型表示的Bean,反而会很糟糕,这时可以使用自定义属性编辑器,在setAsText()方法中将字面值转化为属性类型对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值