# 3.3.2. 내장 된 PropertyEditor구현

Spring은 `Object` 과 `String`간의 변환 `PropertyEditor`개념을 사용하여 수행합니다. 객체 자체와 다른 방식으로 프로퍼티를 표현하는 것이 편리 할 수 ​​있습니다. 예를 들어, `Date` 는 사람이 읽을 수있는 방식으로 ( `String`같이 `'2007-14-09'`) 나타낼 수 있지만, 사람이 읽을 수있는 형식을 원래 날짜로 다시 변환 할 수 있습니*다 (또는* 더 나은 방법으로 사람이 읽을 수있는 어떤 형식도 다시 `Date`개체 로 변환 할 수 있습니다 ). 이 동작은 `java.beans.PropertyEditor`유형의 사용자 정의 편집기를 등록하여 수행 할 수 있습니다. `BeanWrapper`나 이전 챕터에서 얘기했던 대안적인 특정 IoC 컨테이너에 커스텀 에디터를 등록하면 어떻게 프로퍼티를 원하는 타입으로 변환하는 지 알려준다.  자세한 내용은[`java.beans`오라클 패키지](https://docs.oracle.com/javase/8/docs/api/java/beans/package-summary.html) 의 [자바 스크립트의 javadoc을](https://docs.oracle.com/javase/8/docs/api/java/beans/package-summary.html)`PropertyEditor` 참조하십시오 [.](https://docs.oracle.com/javase/8/docs/api/java/beans/package-summary.html)

Spring에서 속성 편집이 사용되는 몇 가지 예 :<br>

* `PropertyEditor`를 사용해서 빈에 프로퍼티를 설정한다. XML 파일에 선언한 어떤 빈의 프로퍼티 값으로 java.lang.String을 사용했을 때 스프링은 (해당 프로퍼티의 setter가 Class-parameter를 가지고 있다면)파라미터를 Class 객체로 처리하려고 `ClassEditor`를 사용할 것이다.
* 스프링 MVC 프레임워크에서 HTTP 요청 파라미터의 파싱은`CommandController`의 모든 하위클래스에 수동으로 연결할 수 있는 모든 종류의 `PropertyEditor`를 사용해서 이뤄진다.

Spring은 삶을 쉽게 만들어 주는 여러 가지 내장 된 `PropertyEditor`구현을 가지고있다. 그들은 모두 `org.springframework.beans.propertyeditors` 패키지에 들어 있습니다. 대부분의 경우 (다음 표에 표시된대로 모두는 아님) 기본적으로에 `BeanWrapperImpl`의해 등록됩니다. 속성 편집기를 어떤 방식으로 구성 할 수있는 곳에서는 자신 만의 변형을 등록하여 기본 변형을 재정의 할 수 있습니다. 다음 테이블은 `PropertyEditor`Spring이 제공 하는 다양한 구현을 설명 합니다.

| 표 12. 기본 제공               |                                                                                                                                                                                                                               |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PropertyEditor`          |                                                                                                                                                                                                                               |
| class                     | 설명                                                                                                                                                                                                                            |
| `ByteArrayPropertyEditor` | 바이트 배열 용 편집기. **문자열을 해당 바이트 표현으로 변환**합니다. `BeanWrapperImpl`에 의해 기본적으로 등록됩니다.                                                                                                                                                  |
| `ClassEditor`             | 클래스를 나타내는 문자열을 실제의 클래스에 해석하거나, 그 역의 경우도 해석합니다. **(클래스로 파싱하거나 그 반대로 파싱)** 클래스가 발견되지 않으면, `IllegalArgumentException`가 throw됩니다. 기본적으로 `BeanWrapperImpl`에 의해 등록됩니다.                                                              |
| `CustomBooleanEditor`     | **`Boolean`속성에 대한 사용자 정의 가능한 속성 편집기.** `BeanWrapperImpl`의 기본값으로 등록되었지만 사용자 정의 편집기로 사용자 정의 인스턴스를 등록하여 재정의 할 수 있습니다.                                                                                                            |
| `CustomCollectionEditor`  | **모든 소스 `Collection`를 지정된 대상 `Collection`유형으로 변환**하는 콜렉션의 특성 편집기 .                                                                                                                                                            |
| `CustomDateEditor`        | **`java.util.Date`사용자 정의 속성 편집기**, `DateFormat`사용자 정의 지원. 기본적으로 등록되지 않았습니다. 필요에 따라 적절한 형식으로 사용자 등록해야합니다.                                                                                                                      |
| `CustomNumberEditor`      | `Integer`, `Long`, `Float`, 또는 `Double`와 같은 **`Number`타입의 서브 클래스를 위한 사용자 정의 속성 편집기.** 기본적으로 등록 `BeanWrapperImpl`되었지만 사용자 정의 편집기로 사용자 정의 인스턴스를 등록하여 재정의 할 수 있습니다.                                                              |
| `FileEditor`              | **문자열을 `java.io.File`객체로 해석 합니다.** 기본적으로 `BeanWrapperImpl`에 의해 등록됩니다.                                                                                                                                                         |
| `InputStreamEditor`       | **`InputStream` 속성이 직접 문자열로 설정할 수 있도록 문자열을 가지고 `InputStream`을 생성**하는  (중간 편도 속성 편집기 `ResourceEditor`및 `Resource` 에 의해 생성 할 수 있습니다 ) 단방향 프로퍼티 에디터이다. 기본 사용법은 `InputStream`귀하를 위해 닫히지 않습니다 . 기본적으로 `BeanWrapperImpl`에 의해 등록됩니다. |
| `LocaleEditor`            | **문자열을 `Locale`객체로 또는 그 반대로** 해석 할 수 있습니다 (문자열 형식은메소드 *`[country]`*`[variant]`와 동일 함 ). 기본적으로에 의해 등록됩니다 .`toString()LocaleBeanWrapperImpl`                                                                                    |
| `PatternEditor`           | **문자열을 `java.util.regex.Pattern`객체로 또는 그 반대로** 해석 할 수 있습니다.                                                                                                                                                                   |
| `PropertiesEditor`        | 문자열 ( `java.util.Properties`클래스 의 javadoc에 정의 된 형식으로 포맷 됨 )을 **`Properties`객체 로 변환** 할 수 있습니다. 기본적으로 `BeanWrapperImpl`에 의해 등록됩니다.                                                                                             |
| `StringTrimmerEditor`     | **문자열을 다듬는 속성 편집기**. 선택적으로 빈 문자열을 `null`값 으로 변환 할 수 있습니다 . 기본적으로 등록되지 않음 - 사용자가 등록해야합니다.                                                                                                                                      |
| `URLEditor`               | **URL의 문자열 표현을 실제 `URL`객체로 해**석 할 수 있습니다. 기본적으로 `BeanWrapperImpl`에 의해 등록됩니다.                                                                                                                                                  |

**Spring은 `java.beans.PropertyEditorManager`을 사용하여 필요한 속성 편집기의 검색 경로를 설정**합니다. 검색 경로도 `sun.bean.editors`포함하여,  `Font`, `Color`및 대부분의 기본 유형과 같은  유형의 `PropertyEditor`구현을 포함합니다.

또한 표준 JavaBeans 인프라 스트럭처 `PropertyEditor`는 처리하는 클래스와 동일한 패키지에 있고  `Editor` 와 함께 해당 클래스와 동일한 이름을 추가 하면 클래스를 명시 적으로 등록 할 필요없이 자동으로 검색 합니다 . 예를 들어, 다음과 같은 클래스 및 패키지 구조를 가질 수 있습니다. 이는 `SomethingEditor`클래스가 인식되어 `PropertyEditor`for `Something`유형화 된 특성 으로 사용되기 에 충분합니다.

```java
com
  chank
    pop
      Someting
      SomethingEditor // Something 클래스의 PropertyEditor
```

당신은 또한 표준 사용할 수 있습니다 `BeanInfo`(어느 정도 설명뿐만 아니라 여기에 자바 빈즈 메커니즘을 [여기에](https://docs.oracle.com/javase/tutorial/javabeans/advanced/customization.html) ). 다음 예제에서는 `BeanInfo`메커니즘을 사용하여 하나 이상의 `PropertyEditor`인스턴스를 연관된 클래스의 속성 으로 명시 적으로 등록합니다 .

```java
com
  chacnk
    pop
      Something
      SomethingBeanInfo // Something 클래스의 BeanInfo
```

참조 된 `SomethingBeanInfo`클래스 의 다음 Java 소스 코드는 a `CustomNumberEditor`를 클래스 의 `age`속성 과 연결합니다 `Something`.

```java
public class SomethingBeanInfo extends SimpleBeanInfo {

    public PropertyDescriptor[] getPropertyDescriptors() {
        try {
            final PropertyEditor numberPE = new CustomNumberEditor(Integer.class, true);
            PropertyDescriptor ageDescriptor = new PropertyDescriptor("age", Something.class) {
                public PropertyEditor createPropertyEditor(Object bean) {
                    return numberPE;
                };
            };
            return new PropertyDescriptor[] { ageDescriptor };
        }
        catch (IntrospectionException ex) {
            throw new Error(ex.toString());
        }
    }
}
```

**추가 사용자 지정 PropertyEditor구현 등록**

빈 속성을 문자열 값으로 설정할 때 Spring IoC 컨테이너는 표준 자바 빈즈 `PropertyEditor`구현을 사용 하여 이러한 문자열을 속성의 복합 유형으로 변환한다. Spring은 많은 커스텀 `PropertyEditor`구현 (예를 들어 문자열로 표현 된 클래스 이름을 `Class`객체 로 변환)을 미리 등록한다 . 또한 Java의 표준 JavaBeans `PropertyEditor`검색 메커니즘을 사용하면 `PropertyEditor` 클래스의 이름을 적절하게 지정하고 지원 클래스를 제공하는 패키지와 동일한 패키지에 배치하여 자동으로 찾을 수 있습니다.

다른 관례를 등록 할 필요가있는 경우에 `PropertyEditors`, 몇몇 기계 장치는 유효하다. 일반적으로 편리하지 않거나 권장되지 않는 가장 수동적 인 방법 은 참조 가 있다고 가정 `registerCustomEditor()`하고 `ConfigurableBeanFactory`인터페이스 의 메소드 를 사용하는 것입니다 `BeanFactory`. 또 다른 (약간 더 편리한) 메커니즘은 호출 된 특별한 bean factory post-processor를 사용하는 것 `CustomEditorConfigurer`입니다. 빈 factory 후 처리기를 `BeanFactory`구현 과 함께 사용할 수 있지만 `CustomEditorConfigurer`중첩 된 속성 설정이 있으므로 `ApplicationContext`다른 bean과 비슷한 방식으로 배포 할 수 있으며 자동으로 감지 할 수있는 위치 와 함께 사용하는 것이 좋습니다. 적용된.

모든 bean 팩토리와 어플리케이션 컨텍스트는 사용법 a `BeanWrapper`를 통해 속성 변환을 처리 하는 다수의 내장 된 속성 편집기를 자동으로 사용합니다 . 표준 속성은 `BeanWrapper` 레지스터가 [이전 섹션에](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-beans-conversion) 나열되어 [있는](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-beans-conversion) 것을 편집합니다 . 또한 `ApplicationContexts`특정 응용 프로그램 컨텍스트 유형에 적합한 방식으로 리소스 조회를 처리하는 추가 편집기를 재정의하거나 추가하십시오.

표준 JavaBeans `PropertyEditor`인스턴스는 문자열로 표현 된 속성 값을 속성의 실제 복합 유형으로 변환하는 데 사용됩니다. 당신이 사용할 수있는 `CustomEditorConfigurer`편리 추가에 대한 지원을 추가하려면, 빈 공장 포스트 프로세서를 `PropertyEditor`에 인스턴스 `ApplicationContext`.

호출 된 사용자 클래스 `ExoticType`와 호출 된 다른 클래스 를 정의하는 다음 예제를 고려해보십시오.이 클래스 는 속성으로 설정 `DependsOnExoticType`해야 `ExoticType`합니다.

```java
package example;

public class ExoticType {

    private String name;

    public ExoticType(String name) {
        this.name = name;
    }
}

public class DependsOnExoticType {

    private ExoticType type;

    public void setType(ExoticType type) {
        this.type = type;
    }
}
```

일이 제대로 설정되면 type 속성을 문자열 `PropertyEditor`로 지정하여 실제 `ExoticType`인스턴스 로 변환 할 수 있기를 원합니다 . 다음 bean 정의는이 관계를 설정하는 방법을 보여줍니다.

```java
<bean id="sample" class="example.DependsOnExoticType">
    <property name="type" value="aNameForExoticType"/>
</bean>
```

`PropertyEditor`구현은 다음과 유사 할 수 :

```java
// converts string representation to ExoticType object
package example;

public class ExoticTypeEditor extends PropertyEditorSupport {

    public void setAsText(String text) {
        setValue(new ExoticType(text.toUpperCase()));
    }
}
```

마지막으로, 다음 예는 사용하는 방법을 보여줍니다 `CustomEditorConfigurer`새로운 등록 `PropertyEditor`와`ApplicationContext`다음 필요에 따라 사용할 수 있습니다 어떤을 :

```java
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
        <map>
            <entry key="example.ExoticType" value="example.ExoticTypeEditor"/>
        </map>
    </property>
</bean>
```

**사용 PropertyEditorRegistrar**

Spring 컨테이너에 속성 에디터를 등록하는 또 다른 메커니즘은 a `PropertyEditorRegistrar`. 이 인터페이스는 여러 가지 상황에서 동일한 속성 편집기 집합을 사용해야하는 경우 특히 유용합니다. 해당하는 등록 기관을 작성하고 각각의 경우에 다시 사용할 수 있습니다. `PropertyEditorRegistrar`인스턴스 `PropertyEditorRegistry`는 스프링 `BeanWrapper`(and `DataBinder`)에 의해 구현 된 인터페이스라는 인터페이스와 함께 작동 합니다. `PropertyEditorRegistrar`인스턴스는 특히 [여기에](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-beans-conversion-customeditor-registration)`CustomEditorConfigurer` 설명 된 속성 과 함께 사용할 때 편리 합니다 . 이 방식 으로 에 추가 된 인스턴스 는 다음과 쉽게 공유 할 수 있습니다.`setPropertyEditorRegistrars(..)PropertyEditorRegistrarCustomEditorConfigurerDataBinder`스프링 MVC 컨트롤러. 또한 맞춤 편집기에서 동기화가 필요하지 않습니다.`PropertyEditorRegistrar` 는 `PropertyEditor` 각 빈 생성 시도에 대해 신선한 인스턴스 를 생성 할 것으로 예상됩니다 .

다음 예제는 사용자 고유의 `PropertyEditorRegistrar`구현 을 만드는 방법을 보여줍니다 .

```java
package com.foo.editors.spring;

public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

    public void registerCustomEditors(PropertyEditorRegistry registry) {

        // it is expected that new PropertyEditor instances are created
        registry.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());

        // you could register as many custom property editors as are required here...
    }
}
```

`org.springframework.beans.support.ResourceEditorRegistrar`예제를 참조하십시오.`PropertyEditorRegistrar` 구현에 . `registerCustomEditors(..)`메서드 구현시 각 속성 편집기의 새 인스턴스를 만드는 방법에 유의하십시오.

다음 예는 `CustomEditorConfigurer`우리의 인스턴스 를 구성하고 인스턴스를 삽입하는 방법을 보여줍니다 `CustomPropertyEditorRegistrar`.

```java
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <ref bean="customPropertyEditorRegistrar"/>
        </list>
    </property>
</bean>

<bean id="customPropertyEditorRegistrar"
    class="com.foo.editors.spring.CustomPropertyEditorRegistrar"/>
```

마지막으로 (그리고 사용 당신의 사람들을 위해이 장의 초점에서 출발의 비트에 [Spring의 MVC 웹 프레임 워크를](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc) ) 사용하여 `PropertyEditorRegistrars`데이터 바인딩과 함께 `Controllers`(같은 것은 `SimpleFormController`) 매우 편리 할 수 있습니다. 다음 예제에서는 메서드 `PropertyEditorRegistrar`구현시에를 `initBinder(..)`사용합니다.

```java
public final class RegisterUserController extends SimpleFormController {

    private final PropertyEditorRegistrar customPropertyEditorRegistrar;

    public RegisterUserController(PropertyEditorRegistrar propertyEditorRegistrar) {
        this.customPropertyEditorRegistrar = propertyEditorRegistrar;
    }

    protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception {
        this.customPropertyEditorRegistrar.registerCustomEditors(binder);
    }

    // other methods to do with registering a User
}
```

이 스타일의 `PropertyEditor`등록은 간결한 코드 ( `initBinder(..)`한 줄만 구현 됨)로 이어질 수 있으며 공통 `PropertyEditor` 등록 코드를 클래스에 캡슐화 한 다음 `Controllers`필요한 만큼 공유 할 수 있습니다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wannaqueen.gitbook.io/spring5/spring-5.0/3.-by-ys-sh/3.3.-bean-beanwrapper-by-ys/3.3.2.-propertyeditor.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
