Spring CustomPropertyEditor

Spring CustomPropertyEditor


이전에 살펴 봤던 Spring 내장 PropertyEditor 대신 이제는 직접 PropertyEditor를 만들고 적용하는 방법을 알아보자. 



사용이유

  • 사용자가 직접 생성한 Class를 value주입을 통해서 property에 주입하고자 할 때

일반적인 bean정의시 사용자가 생성한 Human Class같은 경우 별도의 bean을 생성하여 다른 bean property에 직접 주입하여 주어야 한다.

또한 이런 방법으로 생성되면 singletone으로 생성 되기 때문에 다양한 값을 입력하는 경우 매번 bean을 정의해야 하는 번거로움이 존재한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- Human bean 별도 생성 -->
<bean id="human" class="com.javaking.bean.Human">
     <property name="name">
         <value>이지수</value>
     </property>
     <property name="age">
         <value>1</value>
     </property>
</bean>
 
<bean id="simple" class="com.javaking.bean.SimpleJavaBean">
     <property name="man">
         <ref bean="human"/>
     </property>
</bean>
cs


하지만, CustomPropertyEditor를 등록하면 아래와 같이 문자열을 통해서 bean을 자동생성하여 value주입하는 것이 가능하다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- CustomPropertyEditor 등록 -->
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
        <map>
            <!-- com.javaking.bean.Human 타입의 객체인 경우 -->
            <entry key="com.javaking.bean.Human">
                <bean class="com.javaking.propertyeditor.HumanPropertyEditor"/>
            </entry>
        </map>
    </property>
</bean>
     
<!-- CustomPropertyEditor를 이용한 bean 정의 -->
<bean id="simple" class="com.javaking.bean.SimpleJavaBean">
    <property name="man"><value>이지수 31</value></property>
</bean> 
cs


사용방법

  • CustomPropertyEditor 작성
    • jdk1.5 이상 : java.beans.PropertyEditorSupport Class를 상속 / jdk 1.4이하 : java.beansPropertyEditor interface를 구현
    • setAsText 메소드를 Override 하여 메소드 내부에서 setValue(value) 를 호출
    • value = 주입할 객체
  • application context 파일에 CustomPropertyEditor 등록
    • org.springframework.beans.factory.config.CustomEditorConfigurer을 class로 하는 bean을 등록
    • customEditors Property에 map에 대상 클래스와 처리할 Editor를 지정한다.


 


Example

 

[Human Class]

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
package com.javaking.bean;
 
public class Human {
 
    int age;        // 나이
    String name;    // 이름 
    
    public Human(){
        
    }
    
    public Human(String name, int age) {
        this.age = age;
        this.name = name;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public String getName() {
        return name;
    }
    
}
cs


[SimpleJavaBean Class]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.javaking.bean;
 
public class SimpleJavaBean {
    
    private Human man;
 
    public Human getMan() {
        return man;
    }
    
    public void setMan(Human man) {
        this.man = man;
    }
 
}
cs


[HumanPropertyEditor Class]

setAsText 메소드를 Override 한다.

입력된 스트링을 기반으로 원하는 객체를 생성하고, 대상 객체를 setValue(val)을 통해서 세팅하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.javaking.propertyeditor;
 
import java.beans.PropertyEditorSupport;
 
import com.javaking.bean.Human;
 
// JDK 1.4 이하버젼은 java.beans.PropertyEditor Interface를 구현해야 함
public class HumanPropertyEditor extends PropertyEditorSupport {
    
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String[] strArr = text.split("\\s"); // 스페이스로 문자열 자름
        Human value = new Human(strArr[0], Integer.parseInt(strArr[1]));
        setValue(value);
    }
    
}
cs


[app-context.xml]

app-context에 CustomEditorConfigurer를 등록한다.

CustomEditorConfigurer property customEditors에 customPropertyEditor를 등록한다

이때, key는 처리 대상 Class타입이 되고, 값은 처리 할 CustomPropertyEditor가 된다.

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
<?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">
    
    <!-- CustomPropertyEditor 등록 -->
     <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <!-- com.javaking.bean.Human 타입의 객체인 경우 -->
                <entry key="com.javaking.bean.Human">
                    <!-- HumanPropertyEditor를 통해 객체를 주입하십시오  -->
                    <bean class="com.javaking.propertyeditor.HumanPropertyEditor"/>
                </entry>
            </map>
        </property>
    </bean>
     
     <!-- CustomPropertyEditor를 이용한 bean 정의 -->
    <bean id="simple" class="com.javaking.bean.SimpleJavaBean">
        <property name="man"><value>이지수 31</value></property>
    </bean
    
</beans>
cs


[MainApplication Class]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.context.support.GenericXmlApplicationContext;
 
import com.javaking.bean.SimpleJavaBean;
 
public class MainApplication {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GenericXmlApplicationContext appCtx = new GenericXmlApplicationContext();
        appCtx.load("classpath:META-INF/spring/app-context.xml");
        appCtx.registerShutdownHook();
        appCtx.refresh();
        
        SimpleJavaBean bean = (SimpleJavaBean ) appCtx.getBean("simple");
        
        System.out.println("NAME : " + bean.getMan().getName());
        System.out.println("AGE : "  + bean.getMan().getAge());
 
    }
 
}
cs


 

수행결과

 NAME : 이지수

 AGE : 31



다운로드


CustomPropertyEditor.zip



같이보기


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

Spring Resource  (1) 2016.01.10
Spring ApplicationEvent  (0) 2016.01.10
Spring MessageSource 국제화  (0) 2016.01.08
Spring PropertyEditor  (0) 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