Spring Default Property Editors

0

A property editor is a feature of the JavaBeans API for converting property values to and from text values.

Spring extends java.beans.PropertyEditorSupport to build the custom editors.

When spring instantiates the bean, it relies on the registered custom editors to convert the value provided to its proper type. Each property editor is designed for a certain type of property only.

Spring by default, comes with several property editors for converting common data types. For example, for Number, Class, Class[], File etc. Apart from the default editors, you can also build your own custom editor and register it. In this article, we will see examples of all the default property editors.

This example uses the following frameworks:

  1. Maven 3.2.3
  2. Spring 4.1.5.RELEASE
  3. Eclipse  as the IDE, version Luna 4.4.1.

Dependencies

Add the following dependencies:

  1. spring-core
  2. spring-context
  3. spring-beans

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javarticles.spring</groupId>
	<artifactId>springListExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>		
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>

</project>

Spring default property editors

Spring comes with default property editors for converting the below types:

  1. File
  2. URL
  3. Charset
  4. Class
  5. Class[]
  6. Currency
  7. InputStream
  8. InputSource
  9. Locale
  10. Pattern
  11. Properties
  12. Resource[]
  13. TimeZone
  14. UUID
  15. byte[]
  16. char[]
  17. char
  18. boolean
  19. double
  20. String[]

Let’s create a simple test bean which contains properties for all of the above types.

TestBean:

package com.javarticles.spring;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Currency;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Pattern;

import org.springframework.core.io.Resource;
import org.xml.sax.InputSource;

public class TestBean {
    private File file;
    private URL url;
    private Charset charset;
    private Class<?> clazz;
    private Class<?>[] clazzArray;
    private Currency currency;
    private InputStream inputStream;    
    private InputSource inputSource;
    private Locale locale;
    private Pattern pattern;
    private Properties properties;
    private Resource[] resources;
    private TimeZone timeZone;
    private UUID uuid;
    private byte[] bytes;
    private char[] charArray;
    private char character;
    private boolean bool;
    private double doubleValue;
    private String[] stringArray;    
        

    public String[] getStringArray() {
        return stringArray;
    }

    public void setStringArray(String[] stringArray) {
        this.stringArray = stringArray;
    }

    public double getDoubleValue() {
        return doubleValue;
    }

    public void setDoubleValue(double doubleValue) {
        this.doubleValue = doubleValue;
    }

    public boolean isBool() {
        return bool;
    }

    public void setBool(boolean bool) {
        this.bool = bool;
    }

    public char getCharacter() {
        return character;
    }

    public void setCharacter(char character) {
        this.character = character;
    }

    public char[] getCharArray() {
        return charArray;
    }

    public void setCharArray(char[] charArray) {
        this.charArray = charArray;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

    public UUID getUuid() {
        return uuid;
    }

    public void setUuid(UUID uuid) {
        this.uuid = uuid;
    }

    public TimeZone getTimeZone() {
        return timeZone;
    }

    public void setTimeZone(TimeZone timeZone) {
        this.timeZone = timeZone;
    }

    public Resource[] getResources() {
        return resources;
    }

    public void setResources(Resource[] resources) {
        this.resources = resources;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }

    public void setClazzArray(Class<?>[] clazzArray) {
        this.clazzArray = clazzArray;
    }
    
    public Class<?> getClazz() {
        return clazz;
    }

    public Class<?>[] getClazzArray() {
        return clazzArray;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputSource getInputSource() {
        return inputSource;
    }

    public void setInputSource(InputSource inputSource) {
        this.inputSource = inputSource;
    }

    public Currency getCurrency() {
        return currency;
    }

    public void setCurrency(Currency currency) {
        this.currency = currency;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

    public Charset getCharset() {
        return charset;
    }

    public void setCharset(Charset charset) {
        this.charset = charset;
    }              
}

We will define TestBean in the spring context and set its property values.

<?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:context="http://www.springframework.org/schema/context"
	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/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<bean id="testBean" class="com.javarticles.spring.TestBean">
		<property name="file" value="classpath:/myFile.txt"/>
		<property name="url" value="classpath:/myFile.txt"/>
		<property name="charset" value="UTF-8"/>
		<property name="clazz" value="com.javarticles.spring.ClassA"/>
		<property name="clazzArray">
			<array>
			<value>com.javarticles.spring.ClassA</value>
			<value>com.javarticles.spring.ClassB</value>
			</array>
		</property>
		<property name="currency" value="INR"/>
		<property name="inputStream" value="classpath:/myFile.txt"/>
		<property name="inputSource" value="classpath:/myInputSource.xml"/>
		<property name="locale" value="fr_FR"/>
		<property name="pattern" value="/foo/*"/>
		<property name="properties" value="lang=spring\ntopic=propertyEditor"/>
		<property name="resources" value="classpath*:my*"/>
		<property name="timeZone" value="Asia/Calcutta"/>
		<property name="uuid" value="97300000-4df0-22ce-e25c-20c73d2ef00e"/>
		<property name="bytes" value="This is bytes"/>
		<property name="charArray" value="This is char[]"/>
		<property name="character" value="X"/>
		<property name="bool" value="true"/>
		<property name="doubleValue" value="3.2d"/>
		<property name="stringArray" value="a, b, c, d, e"/>
	</bean>
</beans>

Let’s go through each property.

File Type PropertyEditor

FileEditor is the property editor class supporting this type. You need to specify the file name in the value attribute. The file name can be in the URL form, for example, file:/C:/javarticles_ws/springPropertyEditorExample/target/classes/myFile.txt or in the form of the Spring’s special classpath: pseudo-URL.

<property name="file" value="classpath:/myFile.txt"/>

For backwards compatibility sake, it also accepts absolute file path.

URL Type PropertyEditor

The property editor class supporting URL type is URLEditor. This is similar to the file type. A URL must specify a valid protocol, else it will throw IllegalArgumentException.

<property name="url" value="classpath:/myFile.txt"/>

InputStream Type PropertyEditor

InputStreamEditor is a one-way property editor which can convert from a text String to a java.io.InputStream so given an input stream it won’t be able to convert it back to text.

<property name="inputStream" value="classpath:/myFile.txt"/>

InputSource Type PropertyEditor

InputSourceEditor is the editor for org.xml.sax.InputSource, converting from a Spring resource location String to a SAX InputSource object.

<property name="inputSource" value="classpath:/myInputSource.xml"/>

Charset Type PropertyEditor

CharsetEditor translates the charset String representations into Charset objects and back.

<property name="charset" value="UTF-8"/>

Class Type Property

ClassEditor is the property editor for the Class type. You need to specify the fully qualified name of the class, for example, java.lang.String or java.lang.String[] if it the string array String[].

<property name="clazz" value="com.javarticles.spring.ClassA"/>

Class Array Type Property

ClassArrayEditor is the property editor for an array of classes.

<property name="clazzArray">
    <array>
        <value>com.javarticles.spring.ClassA</value>
	<value>com.javarticles.spring.ClassB</value>
    </array>
</property>

Currency Type Property

CurrencyEditor is the editor for java.util.Currency. It accepts, currency codes in the value attribute and converts them into Currency object.

<property name="currency" value="INR"/>

Locale Type PropertyEditor

LocaleEditor is the class that supports text to Locale conversion. The value to be specified must be in the format of language + optionally country. The optional component is separated by either “_” or space.

<property name="locale" value="fr_FR"/>

Pattern Type PropertyEditor

PatternEditor is the class that supports the pattern. It accepts any pattern that compiles. If passed the same string to Pattern.compile, it should able to convert the text to a Pattern object.

<property name="pattern" value="/foo/*"/>

Properties Type PropertyEditor

PropertiesEditor is the class that converts the properties text to Properties object. Each property must be on a new line.

<property name="properties" value="lang=spring\ntopic=propertyEditor"/>

Resource Array Type PropertyEditor

ResourceArrayPropertyEditor is the class converting location patterns to Resource array properties.

<property name="resources" value="classpath*:my*"/>

We have two files starting with my so it should return us both the resources myFile.txt and myInputSource.xml.

TimeZone Type PropertyEditor

TimeZoneEditor is the class to convert the time zone string into a TimeZone object.

<property name="timeZone" value="Asia/Calcutta"/>

UUID Type PropertyEditor

UUIDEditor is the class that converts the UUID string into UUID object. It internally calls UUID.fromString(string).

<property name="uuid" value="97300000-4df0-22ce-e25c-20c73d2ef00e"/>

Byte Array Type PropertyEditor

ByteArrayPropertyEditor is the class that converts the strings into their corresponding byte representations.

<property name="bytes" value="This is bytes"/>

Character Array Type PropertyEditor

CharArrayPropertyEditor is the class that converts the strings into character array.

<property name="charArray" value="This is char[]"/>

Character Type PropertyEditor

CharEditor is the class to populate the char from a String value. By default, it won’t allow empty value. You can also set unicode character. It should start with \u. If the length of string is more than 1 than spring will throw IllegalArgumentException

<property name="character" value="X"/>

Boolean Type PropertyEditor

CustomBooleanEditor is the class that converts “true”, “false”, “yes”, “no”, “on”, “off”, “1” and “0” to the boolean form.

<property name="bool" value="true"/>

Number Type PropertyEditor

CustomNumberEditor is the class that converts a numeric string to bean’s numeric type Short, Integer, Long, BigInteger, Float, Double or BigDecimal. In the below example, we convert the string to double type.

<property name="doubleValue" value="3.2d"/>

String Array Type PropertyEditor

StringArrayPropertyEditor class converts comma separated string to String array.

<property name="stringArray" value="a, b, c, d, e"/>

Run the example

Let’s load the context and verify each bean to make sure the values passed in are OK and the property editor has converted it properly.

SpringPropertyEditorExample:

package com.javarticles.spring;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class SpringPropertyEditorExample {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            TestBean testBean = (TestBean) context.getBean("testBean");
            System.out.println("file: " + testBean.getFile());
            printContent(testBean.getFile());
            System.out.println("url: " + testBean.getUrl());
            printContent(new File(testBean.getUrl().getFile()));
            System.out.println("Charset: " + testBean.getCharset());
            System.out.println("Class: " + testBean.getClazz());
            System.out.println("Class Array: " + Arrays.asList(testBean.getClazzArray()));
            System.out.println("Currency: " + testBean.getCurrency());
            System.out.println("Input Source: " + testBean.getInputSource());
            System.out.println("Input Stream: " + testBean.getInputStream());
            System.out.println("Locale: " + testBean.getLocale());
            System.out.println("Pattern: " + testBean.getPattern());
            System.out.println("Properties: " + testBean.getProperties());
            System.out.println("Resources:");
            for (Resource resource : testBean.getResources()) {
                System.out.println("location: " + resource.getFile().getCanonicalPath());
            }
            System.out.println("TimeZone: " + testBean.getTimeZone());
            System.out.println("UUID: " + testBean.getUuid().getMostSignificantBits());
            System.out.println("bytes in string form: " + new String(testBean.getBytes()));
            System.out.println("char array in string form: " + new String(testBean.getCharArray()));
            System.out.println("character: " + testBean.getCharacter());
            System.out.println("boolean value: " + testBean.isBool());
            System.out.println("double value: " + testBean.getDoubleValue()); 
            System.out.println("String array: " + Arrays.asList(testBean.getStringArray()));
        } finally {
            context.close();
        }
    }

    private static void printContent(File file) throws IOException {
        String line;
        InputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,
                Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            br.close();
        }
    }
}

Output:

file: C:\javarticles_ws\springPropertyEditorExample\target\classes\myFile.txt
Spring Property Editor Example
url: file:/C:/javarticles_ws/springPropertyEditorExample/target/classes/myFile.txt
Spring Property Editor Example
Charset: UTF-8
Class: class com.javarticles.spring.ClassA
Class Array: [class com.javarticles.spring.ClassA, class com.javarticles.spring.ClassB]Currency: INR
Input Source: [email protected]
Input Stream: [email protected]
Locale: fr_FR
Pattern: /foo/*
Properties: {lang=spring
topic=propertyEditor}
Resources:
location: C:\javarticles_ws\springPropertyEditorExample\target\classes\myFile.txt
location: C:\javarticles_ws\springPropertyEditorExample\target\classes\myInputSource.xml
TimeZone: sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
UUID: -7552536573792738610
bytes in string form: This is bytes
char array in string form: This is char[]
character: X
boolean value: true
double value: 3.2
String array: [a, b, c, d, e]

Download the source code

This was an example about spring’s default property editors.

You can download the source code here: springDefaultPropertyEditorExample.zip
Share.

Comments are closed.