首页 > 代码库 > spring 自定义 Property Editor

spring 自定义 Property Editor

1:集成java.beans.PropertyEditorSupport,并实现(重写)其setAsText()方法

2:在application Context中注册刚刚自定义的类

实例:

1.先弄一个实体类,比如这个Dog:

package fuckSpring.propertyEditor;public class Dog {    private String name;    private String type;    private int age;        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getType() {        return type;    }    public void setType(String type) {        this.type = type;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }        public String toString(){        return this.name+this.type+this.age;    }}

2.下面就是重头戏:MyPropertyEditor

package fuckSpring.propertyEditor;import java.beans.PropertyEditorSupport;public class MyPropertyEditor extends PropertyEditorSupport{    public void setAsText(String s){        String[] ss=s.split("\\|");//  \\作为转义用        Dog d=new Dog();        d.setName(ss[0]);        d.setType(ss[1]);        d.setAge(Integer.parseInt(ss[2]));        setValue(d);//把转化出来的对象设置,spring将会把这个对象赋值给需要的引用    }}

3.定义一个MyTest类,用来测试

package fuckSpring.propertyEditor;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {    private Dog dog;    public Dog getDog() {        return dog;    }    public void setDog(Dog dog) {        this.dog = dog;    }        public static void main(String[] args){        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");        MyTest mt=(MyTest) ac.getBean("myTest");        System.out.println(mt.getDog());    }    }

4,配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans>    <bean name="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">        <property name="customEditors">            <map>                <entry key="fuckSpring.propertyEditor.Dog" value="fuckSpring.propertyEditor.MyPropertyEditor">                </entry>                <!-- 本来是用下面被注释掉的方法进行注册PropertyEditor的,因为我的参考书上是这样注册的,但是运行起来报错,说不能映射,后来上网搜了下,看有用上面的方法注册的 -->                <!--                <entry key="fuckSpring.propertyEditor.Dog">                    <bean class="fuckSpring.propertyEditor.MyPropertyEditor"></bean>                </entry>                 -->            </map>        </property>    </bean>        <bean id="myTest" class="fuckSpring.propertyEditor.MyTest">        <property name="dog">            <value>二狗子|泰迪|3</value>        </property>    </bean></beans>

5,最后运行MyTest类,结果控制台输出:

二狗子泰迪3

ps:

简直是完美

 

spring 自定义 Property Editor