1

我是春天的新手。我正在尝试使用 PropertyEditorSupport 实现 CustomPropertyEditor 并在 app-context.xml 中注册 CustomPropertyEditor。请在下面找到代码。

 public class NamePropertyEditor extends PropertyEditorSupport{

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            //String[] name = text.split(":");
            System.out.println("text: "+ text);
            Name result = new Name(text, "randomString");
            setValue(result);
        }
    }



app-context file
    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
            <property name="customEditors">
                <map>
                    <entry key="com.property.bean.Name">
                        <bean class="com.property.editor.NamePropertyEditor"/>
                    </entry>
                </map>
            </property>
        </bean>
<bean id="exampleBean" class="com.start.CustomEditorExample">
        <property name="name">
        <value>Varun Bhatia</value></property>
    </bean>

尝试使用 PropertyEditor 的类

public static void main(String[] args) {

        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("classpath:/META-INF/spring/app-context.xml");
        //ctx.refresh();

        CustomEditorExample bean = (CustomEditorExample) ctx.getBean("exampleBean");

        System.out.println(bean.getName());
    }

    public Name getName() {
        System.out.println("getName");
        return name;
    }
    public void setName(Name name) {
        System.out.println("setName");
        this.name = name;
    }

问题是控制不会使用 setAsText 方法。

4

1 回答 1

0

您编写的代码main()不会调用您的属性编辑器

尝试类似的东西

CustomEditorExample bean = (CustomEditorExample) ctx.getBean("exampleBean");

BeanWrapper wrapper = new BeanWrapperImpl(bean );
wrapper.setPropertyValue("name", "Some Text");//this will invoke your property editor

System.out.println(bean.getName());

我建议你阅读这个Spring Docs

于 2013-08-14T07:53:01.367 回答