Spring propertyEditor

  在Spring框架中,提供了几个内置的属性编辑器,如FileEditor,ResourceEditor等。要想使用自定义属性编辑器,需要经过两个步骤。

 

  一。定义一个自定义编辑器,可实现PropertyEditor接口或直接继承PropertyEditorSupport类。

 

package com.dream.editor;

import com.dream.model.photo.Photo;
import com.dream.service.standard.PhotoService;

import java.beans.PropertyEditorSupport;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-9-6
 * Time: 下午10:10
 */
public class PhotoEditor extends PropertyEditorSupport {
    private PhotoService photoService;

    @Override
    public String getAsText() {
        Photo photo = (Photo) getValue();
        return photo.getGuid();
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Photo photo = photoService.loadPhotoByGuid(text);
        setValue(photo);
    }
}

 

  二。注册自定义编辑器

 

  Spring提供了一个PropertyEditorRegistry接口和PropertyEditorRegistrySupport类来自定义一个注册器。其中PropertyEditorRegistrySupport是Spring提供的一个默认实现,里面注册了一些内置的编辑器。

 

  可以在配置文件中注册自定义编辑器,也可以以编程的方式注册自定义编辑器。

 

 

String location = "testApplicationContext.xml";
        Resource resource = new ClassPathResource(location);
        XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
        beanFactory.registerCustomEditor(Photo.class, PhotoEditor.class);
 

 

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <entry key="com.dream.model.photo.Photo">
                    <ref bean="photoEditor"/>
                </entry>
            </map>
        </property>
    </bean>

    <bean id="photoEditor" class="com.dream.editor.PhotoEditor">
        <property name="photoService" ref="photoService"/>
    </bean>

你可能感兴趣的:(spring,PropertyEditor)