Spring属性编辑器详解

1、常见的属性的注入:int,string,list,set,map

2、什么是属性编辑器及作用?

(1)将spring配置文件中的字符串转换为相应的java对象

(2)spring内置了一些属性编辑器,也可以自定义属性编辑器

3、如果自定义属性编辑器

(1)继承propertyEditorSupport

(2)重写setAsText 方法

(3)使用 setValue 完成属性对象设置

下面通过实例来说明类属性自定义动态加载

工程截图:

工程说明:

1、Education.java 自定义属性(自定义类属性)

2、EducationPropertyEditor.java自定义属性编辑器

3、PropertyDateEditor.java 自定义日期属性编辑器

4、testPropertyEditot 单元测试类

测试结果截图:

代码:

beans.xm文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="PropertyEditorConfigurer1"
        class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <!-- 引用类的属性类型,本例子中对应 com.test.Person 类的 education 属性 东北大亨对应读取的学校属性 -->
                <entry key="com.test.Education">
                    <!--对应Address的编辑器 -->
                    <bean class="com.test.EducationPropertyEditor" />
                </entry>
            </map>
        </property>
    </bean>
    <bean id="PropertyEditorConfigurer2"
        class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <!-- 引用类的属性类型,本例子中对应 com.test.Person 类的 dataValue属性 -->
                <entry key="java.util.Date">
                    <!--对应dataValue 属性的编辑器 -->
                    <bean class="com.test.PropertyDateEditor" >
                        <property name="dataPattern" value="yyyy/MM/dd"/>
                    </bean>
                </entry>
            </map>
        </property>
    </bean>
    <bean id="person" class="com.test.Person">
        <property name="id" value="1003" />
        <property name="name" value="东北大亨" />
        <property name="education" value="中国,北京海淀区清华大学" />
        <property name="dataValue" value="2018/12/30" />
    </bean>
</beans>

测试类 testPropertyEditot:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public class testPropertyEditot extends TestCase {
    
    public void testPrintProperty() {
        System.out.println("测试springPropertyUtil  start");

// 可以同时配置多个xml配置文件,如果多个配置具有一定规则情况下可以采用匹配方式进行读取
        // 例如有两个xml 文件。既:beans-1.xml,beans-2.xml,beans-3.xml
        // 采用匹配方式进行读取
        // ApplicationContext ctx = new
        // ClassPathXmlApplicationContext("beans-*.xml");

// 废弃方法不建议使用
        // BeanFactory factory=new XmlBeanFactory(new
        // ClassPathResource("beans.xml"));

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Person person = (Person) ctx.getBean("person");

System.out.println("学生ID:" + person.getId());
        System.out.println("名称:" + person.getName());
        System.out.println("毕业时间:" + person.getDataValue());
        System.out.println("学生就读国别:" + person.getEducation().getCountry());
        System.out.println("学生就读地址:" + person.getEducation().getDirectory());
        
        assertEquals(person.getId(),1003);
        assertEquals(person.getName(),"东北大亨");

System.out.println("测试springPropertyUtil  end");
    }
}

日期编辑器 PropertyDateEditor :

package com.test;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author 东北大亨
 *
 */
public class PropertyDateEditor extends PropertyEditorSupport {
    
    
    private String dataPattern;

/**
     * Parse the value from the given text, using the SimpleDateFormat
     */
    @Override
    public void setAsText(String text) {
        System.out.println("------UtilDatePropertyEditor.setAsText()------" + text);
        try {
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf = new SimpleDateFormat(dataPattern);
            Date date = new Date();
            date = sdf.parse(text);
            this.setValue(date);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(text);
        }
    }
    
    // 只要有set方法就可以注入进来
    public void setDataPattern(String pattern) {
        this.dataPattern = pattern;
    }
}

人员 Person pojo类:

package com.test;

import java.util.Date;
import org.apache.commons.lang.builder.ToStringBuilder;

/**
 *
 * @author 东北大亨
 *
 */
public class Person {

private int id;
    private String name;
    private Education education;

private Date dataValue;
    
    public int getId() {
        return id;
    }

public void setId(int id) {
        this.id = id;
    }

public Date getDataValue() {
        return dataValue;
    }

public void setDataValue(Date dataValue) {
        this.dataValue = dataValue;
    }

public Education getEducation() {
        return education;
    }

public void setEducation(Education education) {
        this.education = education;
    }

public String getName() {
        return name;
    }

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

public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

实体类属性编辑器:

package com.test;

import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;

/**
 * 实体类编辑器
 * @author 东北大亨
 *
 */
public class EducationPropertyEditor extends PropertyEditorSupport {

@Override
    public void setAsText(String text) {
        if (text == null || !StringUtils.hasText(text)) {
            throw new IllegalArgumentException("就读住址不能为空!");
        } else {
            String[] StrAddressArr = StringUtils.tokenizeToStringArray(text, ",");
            Education add = new Education();
            add.setCountry(StrAddressArr[0]);
            add.setDirectory(StrAddressArr[1]);
            setValue(add);
        }
    }

public String getAsText() {
        Education add = (Education) getValue();
        return "" + add;
    }
}

学校实体类:

package com.test;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * 读取学校实体类
 * @author 东北大亨
 *
 */
public class Education {

private String country;

private String directory;

public String getDirectory() {
        return directory;
    }

public void setDirectory(String directory) {
        this.directory = directory;
    }

public String getCountry() {
        return country;
    }

public void setCountry(String country) {
        this.country = country;
    }

}

原文地址:https://www.cnblogs.com/northeastTycoon/p/spring.html

时间: 2024-08-04 13:11:53

Spring属性编辑器详解的相关文章

一份spring配置文件及其详解

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/axu20/archive/2009/10/14/4668188.aspx 1.基本配置:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/

Spring的lazy-init详解

Spring中lazy-init详解ApplicationContext实现的默认行为就是在启动服务器时将所有singleton bean提前进行实例化(也就是依赖注入).提前实例化意味着作为初始化过程的一部分,applicationContext实例会创建并配置所有的singleton bean.通常情况下这是一件好事,因为这样在配置中的任何错误就会被立刻实现(否则的话可能要话几个小时甚至几天). <bean id="testBean" class="cn.itcas

Spring的AOP详解

Spring的AOP详解 一.AOP基础 1.1AOP是什么 考虑这样一个问题:需要对系统中的某些业务做日志记录,比如支付系统中的支付业务需要记录支付相关日志,对于支付系统可能相当复杂,比如可能有自己的支付系统,也可能引入第三方支付平台,面对这样的支付系统该如何解决呢? 传统解决方案 1.日志部分定义公共类LogUtils,定义logPayBegin方法用于记录支付开始日志, logPayEnd用于记录支付结果 logPayBegin(long userId,long money) logPay

Spring的配置详解

Spring的配置详解 3.1XML配置的结构 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www

转载:Spring MVC配置详解

以下内容引自:http://www.cnblogs.com/superjt/p/3309255.html spring MVC配置详解 现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理. 一.Spring MVC环境搭建:(Spring 2.5.6 + Hiber

spring之ioc详解

第一节:spring IOC的详解 首先想说说IoC(Inversion of Control,控制倒转).这是spring的核心,贯穿始终.所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系.这是什么意思呢,举个简单的例子,我们是如何找女朋友的?常见的情况是,我们到处去看哪里有长得漂亮身材又好的mm,然后打听她们的兴趣爱好.qq号.电话号.ip号.iq号………,想办法认识她们,投其所好送其所要,然后嘿嘿……这个过程是复杂深奥的,我们必须自己设计和面对

js的offsetParent属性用法详解

js的offsetParent属性用法详解:此属性是javascript中较为常用的属性,对于它的良好掌握也是非常有必要的,下面就通过代码实例介绍一下它的用法,希望能够给需要的朋友带来一定的帮助.一.基本介绍:此属性可以返回距离指定元素最近的采用定位(position属性值为fixed.relative或者absolute)父级元素,如果父级元素中没有采用定位的元素,则返回body对象的引用.语法结构: obj.offsetParent 二.代码实例: <!DOCTYPE html> <

linux之vim编辑器详解

字处理器:像word,wps,除了本文本身以外,还有修饰方面的设置. 文本编辑器:编辑纯ASCII文档. nano,sed  入门简单,功能简陋. 强大的vi编辑器 (Visual Interface) 现在是Vim :VI  inproved 它是全屏编辑器,模式化编辑器. vim模式: 编辑模式(命令模式) 输入模式 末行模式 默认处于编辑模式. 模式转化: 编辑模式--->输入模式: i :在当前光标所在字符的前面,转为输入模式. a:在当前光标所在字符的后面,转为输入模式. o:在当前光

offsetleft属性用法详解

offsetleft属性用法详解:本章节通过代码实例介绍一下offsetleft属性的用法,需要的朋友可以做一下参考.此属性可以返回当前元素距离某个父辈元素左边缘的距离,当然这个父辈元素也是有讲究的.(1).如果父辈元素中有定位的元素,那么就返回距离当前元素最近的定位元素边缘的距离.(2).如果父辈元素中没有定位元素,那么就返回相对于body左边缘距离.语法结构: obj.offsetleft 特别说明:此属性是只读的,不能够赋值.代码实例: <!DOCTYPE html> <html&