• Spring自定义属性编辑器


      自定义属性编辑器主要解决在配置文件中,字符串转换为某种类型的对象的问题。  如applicationContext中配置的字符串14,在类中是整数类型的话会自动匹配转换为整数。

    Spring提供了一些常用的属性编辑器,如字符串转日期,数字等。

     自定义属性编辑器:

     1.继承PropertyEditorSupport,重写 getAsText,setAsText方法实现字符串与属性的互相转换。

     2.如果自定义属性编辑器与需要转换的目标类位于同包下,并且名称为 目标类名+Editor,则不需要配置注册,Spring会自己搜索到并注册,否则需要在applicationContext中配置注册。

    public class School {
    
        private Teacher teacher;//持有teacher的引用。
    
        public Teacher getTeacher() {
            return teacher;
        }
    
        public void setTeacher(Teacher teacher) {
            this.teacher = teacher;
        }
    }
    public class Teacher {
    
        private  String name;
        private int age;
        
        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;
        }
        
    }

    applicationContext中配置School bean

    <bean id="school" class="com.zk.School">
        <property name="teacher">
            <value>lisi,25</value>
        </property>
    </bean>

    即我们需要实现字符串"lisi,25" 转换为一个Teahcer对象。

    自定义Teacher属性编辑器:

    import java.beans.PropertyEditorSupport;
    
    public class TeacherEditor extends PropertyEditorSupport {
    
        @Override
        public String getAsText() {//将属性转换为字符串 
            Teacher teacher  = (Teacher)getValue();  //getValue获取当前属性值
            return teacher.getName()+","+teacher.getAge();  //zhangsan,14
        }
        
        
        
        @Override
        public void setAsText(String text) throws IllegalArgumentException {//将字符串转换为属性
            String[] txtArray = text.split(",");
            Teacher teacher = new Teacher();
            teacher.setName(txtArray[0]);
            teacher.setAge(Integer.valueOf(txtArray[1]));
            setValue(teacher);//设置当前的属性
        }
    }


    由于Teacher类 与 TeacherEditor类在同包下,所以不需要在applicationContext中注册编辑器。 上述代码可以直接使用。

    否则需要在CustomEditorConfigurer中注册自定义属性编辑器 如:

    <!-- 自定义属性编辑器的注册 -->
    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <entry key="com.zk.Teacher">
                    <value>com.zk.TeacherEditor222</value>
                </entry>
            </map>
        </property>
    </bean>
  • 相关阅读:
    梯度下降法实现python[转载]
    PAT Maximum Subsequence Sum[最大子序列和,简单dp]
    PAT Sign In and Sign Out[非常简单]
    PAT 1015 Reversible Primes[求d进制下的逆][简单]
    outlook 召回邮件 (zz)
    The Microsoft.Jet.OLEDB.4.0 provider is not registered on the local machine (zz)
    Determine Microsoft Database AccessEngine Version (zz)
    企业的十三中死法
    c#事件学习
    20071017我们的新家
  • 原文地址:https://www.cnblogs.com/beenupper/p/2987423.html
Copyright © 2020-2023  润新知