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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值