Spring PropertyEditor

Spring PropertyEditor


1
2
3
4
5
<bean id="someId" class="com.javaking.SomeClass">
    <property name="foo">
        <value>안녕</value>
    </property>
</bean>
cs


Spring bean 정의시 흔히 쓰이는 간단한 코드이다.


SomeClass의 Bean을 생성하고 맴버변수(property) foo에게 "안녕"이라는 문자열을 주입하고 있다. 이때, foo가 String foo; byte[] foo; Pattern foo; 여도 Spring은 foo가 정의된 Class type에 맞는 객체를 생성하고 주입하여 준다.


당연하게 느껴지겠지만 이와 같은 기능을 해주는 것이 PropertyEditor이다. 

 

즉, PropertyEditor는 문자열로 표현 된 <value>의 값을 <property>의 type에 맞게 객체를 생성하는 역할을 한다.


스프링에서는 다양한 내장 ProeprtyEditor 제공하며, 필요 시 사용자가 정의한 PropertyEditor를 생성하여 등록 하는 것이 가능하다.



내장 PropertyEditor


* 빨간색으로 체크된 Editor는 별도 CustomEditorConfigurer bean에 등록 필요


 내장 PropertyEditor

 설명

 ByteArrayPropertyEditor

 입력된 문자열을 byte 배열로 변환한다. 

 ClassEditor

 입력된 문자열을 전체 Class 인스턴스로 변환한다. GenericXmlApplicationContext를 사용하면서 클래스명 앞 뒤 어느 곳에도 추가 공백이 포함 되지 않아야 한다. ( 공백존재 시 ClassNotFoundException)

 CustomBooleanEditor

 입력된 무자열ㅇ르 Boolean 타입으로 변환한다.

 CustomeCollectionEditor

 소스 컬렉션 (예를들어 util namespace를 사용한 컬렉션)을 대상 Collection 타입으로 변환한다.

 CustomDateEditor

 문자열로 표현한 날짜를 java.util.Date 값으로 변환한다.

 이때 원하는 날짜 형식을 사용해 CustomDateEditor를 스프링 ApplicationContext에 등록해야 한다.

 (org.springframework.beans.factory.config.CustomEditorConfigurer 빈을 정의하고, customEditors에 CustomDateEditor를 등록해야 한다)

 CustomNumberEditor

 문자열을 타깃 숫자 값으로 변환한다. 대상 값은 Integer, Long, Float, Double로 지정 할 수 있다.

 FileEditor

 FileEditor는 문자열 파일 경로를 File 인스턴스로 변환한다.

 InputStreamEditor

 리소스의 문자열 표현 (file:D/temp/a.txt 혹은 classpath:temp/a.txt)을 InputStream 인스턴스로 변환한다.

 LocaleEditor

 로케일 문자표현 (en-US)을 읽어 Locale 인스턴스로 변환한다.

 PatternEditor

 무자열을 Pattern객체로 변환하거나 역으로 변환한다.

 PropertiesEditor

 key1=value1 key2=value2 형식의 문자열을 java.util.Properties인스턴스로변환한다.

 StringTrimmerEditor

 문자열 앞 뒤에 공백을 trim하고 String인스턴스를 변환한다. 

(org.springframework.beans.factory.config.CustomEditorConfigurer 빈을 정의하고, customEditors에 StringTrimmerEditor를 등록해야 한다)

 URLEditor

 URLEditor는 문자열 URL을 java.net.URL인스턴스로 변환한다.

 

 

Example


[SimpleBean Class]

내장 PropertyEditor의 동작을 확인 하기 위해서 다양한 type의 변수들과 set method만 정의 되어 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.javaking.bean;
 
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Pattern;
 
public class SimpleBean {
    private byte[] bytes;                // byteArrayPropertyEditor
    private Class cls;                    // ClassEditor
    private Boolean trueOrFalse;         // CustomBooleanEditor
    private List<String> stringList;    // CustomCollectionEditor
    private Date date;                    // CustomDateEditor
    private Float floatValue;            // CustomNumberEditor
    private File file;                    // CustomFileEditor
    private InputStream stream;            // InputStreamEditor
    private Locale locale;                // LocaleEditor
    private Pattern pattern;            // PatternEditor
    private Properties properties;        // PropertiesEditor
    private String trimString;            // StringTrimmerEditor
    private URL url;                    // URLEditor
 
    public void setBytes(byte[] bytes) {
        System.out.println("Adding " + bytes.length + "bytes");
        this.bytes = bytes;
    }
    public void setCls(Class cls) {
        System.out.println("Setting class : " + cls.getName());
        this.cls = cls;
    }
    public void setTrueOrFalse(Boolean trueOrFalse) {
        System.out.println("Setting Boolean : " + trueOrFalse);
        this.trueOrFalse = trueOrFalse;
    }
    public void setStringList(List<String> stringList) {
        System.out.println("Setting string list with size : " + stringList.size());
        for(String s : stringList) {
            System.out.println("String member : " + s);
        }
        this.stringList = stringList;
    }
    public void setDate(Date date) {
        System.out.println("Setting date : " + date);
        this.date = date;
    }
    public void setFloatValue(Float floatValue) {
        System.out.println("Setting float value : " + floatValue);
        this.floatValue = floatValue;
    }
    public void setFile(File file) {
        System.out.println("Setting file : "+ file.getName());
        this.file = file;
    }
    public void setStream(InputStream stream) {
        System.out.println("Setting stream : "+ stream);
        this.stream = stream;
    }
    public void setLocale(Locale locale) {
        System.out.println("Setting Locale : " + locale.getDisplayName());
        this.locale = locale;
    }
    public void setPattern(Pattern pattern) {
        System.out.println("Setting pattern : " + pattern);
        this.pattern = pattern;
    }
    public void setProperties(Properties properties) {
        System.out.println("Loaded " + properties.size() + "properties");
        this.properties = properties;
    }
    public void setTrimString(String trimString) {
        System.out.println("Setting trim string : " + trimString);
        this.trimString = trimString;
    }
    public void setUrl(URL url) {
        System.out.println("Setting URL : " + url.toExternalForm());
        this.url = url;
    }
    
}
 
 
cs





 [app-context.xml]

CustomDateEditor 혹은 StringTrimmerEditor를 사용하려면 org.springframework.beans.factory.config.CutomEditorConfigurer Class를 bean등록

CustomDateEditor 의 경우 생성자로 SimpleDateFormat 지정하여 bean생성 필요.

StringTrimmerEditor의 경우 등록과 bean 생성만 하면 됨.


핵심은 CutomEditorConfigurer의 property인 customEditors 에 map을 등록하는 부분.

  • key로 지정된 type에 대한 value injection은 지정된 PropertyEditor로 수행
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
 
<?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:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <!-- CustomEditor를 ApplicationContext에 등록 -->
    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        
        <property name="customEditors">
            <map>
                <!-- key 값이 property type이 되고, 지정된 PropertyEditor가 실제 객체를 생성 하는 기능을 수행한다. -->
                
                <!-- Date proeprty는  CustomDateEditor로 생성하세요 -->
                <entry key="java.util.Date">
                    <bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
                        <constructor-arg>
                            <bean class="java.text.SimpleDateFormat">
                                <constructor-arg value="yyyy-MM-dd"/>    
                            </bean>
                        </constructor-arg>    
                        <constructor-arg value="true"/>
                    </bean>
                </entry>
                
                <!-- String proeprty는  StringTrimmerEditor로 생성하세요 -->
                <entry key="java.lang.String">
                    <bean class="org.springframework.beans.propertyeditors.StringTrimmerEditor">
                        <constructor-arg value="true"/>
                    </bean>
                </entry>
                
                <!-- 추가등록 -->
            </map>
        </property>
    </bean>
 
     <!-- 실제 bean에 대한 정의  -->
    <bean id="simpleBean" class="com.javaking.bean.SimpleBean">
         <!-- property type에 맞게 알아서 PropertyEditor가 동작한다. -->
        <property name="date">
            <value>2016-01-04</value>
        </property>
        
        <property name="trimString">
            <value>      String need trimming       </value>
        </property>
         
        <property name="bytes">
            <value>Hello World</value>
        </property>
    
        <property name="cls">
            <value>java.lang.String</value>
        </property>
        
        <property name="trueOrFalse">
            <value>true</value>
        </property>
        
        <property name="stringList">
            <util:list>
                <value>String member 1</value>
                <value>String member 2</value>
            </util:list>
        </property>
        
        <property name="floatValue">
            <value>123.45678</value>
        </property>
        
        <property name="file">
            <value>classpath:test.txt</value>
        </property>
 
        <property name="stream">
            <value>classpath:test.txt</value>
        </property>
        
        <property name="locale">
            <value>en_US</value>
        </property>
        
        <property name="pattern">
            <value>a*b</value>        
        </property>
        
        <property name="properties">
            <value>
                name=foo
                age=19
            </value>
        </property>
        
        <property name="url">
            <value>http://javaking.tistory.com</value>
        </property>
    </bean>
     
</beans>
 
 
cs



 [MainApplication Class]

아무것도 하지 않고 applicationContext만 load 한다. => bean 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainApplication {
 
    public static void main(String[] args) {
        GenericXmlApplicationContext appCtx = new GenericXmlApplicationContext();
        appCtx.load("classpath:META-INF/spring/app-context.xml");
        appCtx.registerShutdownHook();
        appCtx.refresh();
 
    }
 
}
 
cs


수행결과

정상적으로 PropertyEditor가 동작되어 bean이 생성 되었다.

Setting date : Mon Jan 04 00:00:00 KST 2016

Setting trim string : String need trimming

Adding 11bytes

Setting class : java.lang.String

Setting Boolean : true

Setting string list with size : 2

String member : String member 1

String member : String member 2

Setting float value : 123.45678

Setting file : test.txt

Setting stream : java.io.BufferedInputStream@169dc09

Setting Locale : 영어 (미국)

Setting pattern : a*b

Loaded 2properties

Setting URL : http://javaking.tistory.com




다운로드


SpringPropertyEditor.zip



같이보기


'프로그래밍 > Spring FWK' 카테고리의 다른 글

Spring Resource  (1) 2016.01.10
Spring ApplicationEvent  (0) 2016.01.10
Spring MessageSource 국제화  (0) 2016.01.08
Spring CustomPropertyEditor  (2) 2016.01.05
Spring facoty-bean, factory-method  (0) 2015.12.30
Spring FactoryBean Interface  (0) 2015.12.29
Spring ApplicationContextAware Interface  (0) 2015.12.28
Spring BeanNameAware Interface  (1) 2015.12.28

이 글을 공유하기

댓글

Email by JB FACTORY