Spring中内置PropertyEditor

PropertyEditor

JavaBean PropertyEditor接口,将字符串属性值转换成正确的类型;

 Spring中内置PropertyEditor

Spring PropertyEditor
PropertyEditor描述
ByteArrayPropertyEditor将字符串值转换为响应的字节表示形式
CharacterEditor字符串转Character或char类型的属性
ClassEditor指定类名转换为类的实例,类名要精确的字符串;
CustomBooleanEditor字符串转boolean类型
CustomCollectionEditor将源集合转换为目标Collection类型
CustomDateEditor将日期字符串转换为java util date类型,需要在Spring的ApplicationContext中以所需的日期格式注册CustomDateEditor实现;(下面有例子)
FileEditor将String文件路径转换为File实例。(Spring不检查文件是否存在)
InputStreamEditor将资源的字符串转换为输入流属性
LocaleEditor将语言环境的字符串表示形式(en_GB)转换为java.util.Locale实例
PatternEditor将字符串转换为JDK Pattern对象或其他方式
PropertiesEditor以格式k1=v1,k2=v2,kn=vn的字符串转换为配置了响应属性的java.util.Properties实例
StringTrimmerEditor再注入之前对字符串进行修剪;(需要注册该编辑器)
URLEditor将URL的字符串表示形式转换为java.net.URL的实例

 

 

 

 

 

 

 

 

 

 

 

 

例子

CustomDateEditor类是转java.util.Date类型,仿照该类对LocalDateTime类型进行转换;

自定义CustomLocalDateTimeEditor类 

import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateTime 配置器
 *
 * @author YanZhen
 * @since 2019-05-24 13:09
 */
public class CustomLocalDateTimeEditor extends PropertyEditorSupport {
  private final String format;
  private final boolean allowEmpty;
  private final int exactDateLength;

  public CustomLocalDateTimeEditor(String format) {
    this.format = format;
    this.allowEmpty = false;
    this.exactDateLength = -1;
  }

  public CustomLocalDateTimeEditor(String format, boolean allowEmpty) {
    this.format = format;
    this.allowEmpty = allowEmpty;
    this.exactDateLength = -1;
  }

  public CustomLocalDateTimeEditor(String format, boolean allowEmpty, int exactDateLength) {
    this.format = format;
    this.allowEmpty = allowEmpty;
    this.exactDateLength = exactDateLength;
  }

  @Override
  public String getAsText() {
    final LocalDateTime localDateTime = (LocalDateTime) getValue();
    if (localDateTime == null) {
      return "";
    }
    return localDateTime.toString();
  }

  @Override
  public void setAsText(@Nullable String text) throws IllegalArgumentException {
    if (this.allowEmpty && !StringUtils.hasText(text)) {
      // Treat empty String as null value.
      setValue(null);
    } else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
      throw new IllegalArgumentException(
              "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
    } else {
      if (text != null) {
        setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern(format)));// 以什么格式解析
      }
    }
  }
}

PropertyEditorBean测试类

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.support.GenericXmlApplicationContext;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 属性编辑器,测试
 *
 * @author YanZhen
 * @since 2019-05-24 11:41
 */
public class PropertyEditorBean {

  private byte[] bytes;
  private Character character;
  private Class cls;
  private boolean bool;
  private List<String> list;
  private LocalDateTime date;
  private Float floatV;
  private File file;
  private InputStream inputStream;
  private Locale locale;
  private Pattern pattern;
  private Properties properties;
  private String trimString;
  private URL url;

  public static void main(String[] args) {
    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();
    context.load("classpath:spring2/app-context-property-editor.xml");
    context.refresh();
    context.getBean(PropertyEditorBean.class);
    context.close();
  }

  public void setBytes(byte[] bytes) {
    System.out.println("Setter Bytes : " + Collections.singletonList(bytes));
    this.bytes = bytes;
  }

  public void setCharacter(Character character) {
    System.out.println("Setter Character : " + character);
    this.character = character;
  }

  public void setCls(Class cls) {
    System.out.println("Setter Class : " + cls.getName());
    this.cls = cls;
  }

  public void setBool(boolean bool) {
    System.out.println("Setter Boolean : " + bool);
    this.bool = bool;
  }

  public void setList(List<String> list) {
    System.out.println("Setter List : " + list);
    this.list = list;
  }

  public void setDate(LocalDateTime date) {
    System.out.println("Setter LocalDate : " + date);
    this.date = date;
  }

  public void setFloatV(Float floatV) {
    System.out.println("Setter Float : " + floatV);
    this.floatV = floatV;
  }

  public void setFile(File file) {
    System.out.println("Setter File : " + file.getName());
    this.file = file;
  }

  public void setInputStream(InputStream inputStream) {
    System.out.println("Setter InputStream : " + inputStream);
    this.inputStream = inputStream;
  }

  public void setLocale(Locale locale) {
    System.out.println("Setter Locale : " + locale);
    this.locale = locale;
  }

  public void setPattern(Pattern pattern) {
    System.out.println("Setter Pattern : " + pattern);
    this.pattern = pattern;
  }

  public void setProperties(Properties properties) {
    System.out.println("Setter Properties : " + properties);
    this.properties = properties;
  }

  public void setTrimString(String trimString) {
    System.out.println("Setter String : " + trimString);
    this.trimString = trimString;
  }

  public void setUrl(URL url) {
    System.out.println("Setter URL : " + url.toExternalForm());
    this.url = url;
  }

  public static class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
      registry.registerCustomEditor(LocalDateTime.class,
              new CustomLocalDateTimeEditor("yyyy-MM-dd HH:mm:ss"));
      registry.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
  }
}

app-context-property-editor.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

  <!--利用PropertyEditor匹配类型-->
  <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"
        p:propertyEditorRegistrars-ref="propertyEditorRegistrarsList"/>
  <util:list id="propertyEditorRegistrarsList">
    <bean class="com.geo.source.spring_simple.example4_chapter.propertyEditor.PropertyEditorBean$CustomPropertyEditorRegistrar"/>
  </util:list>
  <bean id="builtInSample" class="com.geo.source.spring_simple.example4_chapter.propertyEditor.PropertyEditorBean"
        p:character="A" p:bytes="yz" p:cls="java.lang.String" p:bool="true" p:list="stringList"
        p:inputStream="test.txt" p:floatV="123.45678" p:date="2019-05-24 00:00:01" p:file="test.txt" p:locale="en_US"
        p:pattern="a*b" p:properties="name=yz age=27" p:trimString=" String need trimming " p:url="https://spring.io/"/>
  <util:list id="stringList">
    <value>String member 1</value>
    <value>String member 2</value>
  </util:list>
</beans>

结果

源码

https://github.com/I-want-to-knowledge/test-project

这是我的测试项目,写的比较乱,你只看这个文件夹就行了:

com.geo.source.spring_simple.example4_chapter.propertyEditor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值