PropertyEditor或Converter

PropertyEditor或Converter

本文介绍了Spring MVC类型转换:PropertyEditor或Converter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Spring MVC中绑定和转换数据的最简单和最简单的方法。如果可能,不做任何xml配置。



到目前为止,我一直在使用,如下所示:

  public class CategoryEditor extends PropertyEditorSupport {

//将字符串转换为类别(提交表单时)
@Override
public void setAsText(String text){
类别c =新类别(文字);
this.setValue(c);
}

//将类别转换为字符串(显示窗体时)
@Override
public String getAsText(){
类别c =类别)this.getValue();
return c.getName();
}

}

  ... 
public class MyController {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Category.class,new CategoryEditor());
}

...

}

很简单:两个转换都在同一个类中定义,绑定是直接的。如果我想在所有控制器上执行一般绑定,我仍然可以添加。






但是Spring 3.x引入了一种新的方式来实现,使用:

所以让我们想使用转换器,因为它是最新的替代方案。我必须创建两个转换器:

  public class StringToCategory implements Converter< String,Category> {

@Override
public类别转换(String source){
类别c =新类别(来源);
return c;
}

}

public class CategoryToString实现转换器< Category,String> {

@Override
public String convert(Category source){
return source.getName();
}

}

第一个缺点: / strong>我必须做两个班。好处:不需要投票感谢一般性。



那么,如何简单的数据绑定转换器?



第二个缺点:我没有发现任何简单的方法(注释或其他程序设施)在控制器中执行: code> someSpringObject.registerCustomConverter(...); 。



我发现的唯一方法是乏味,不简单,并且只涉及一般的交叉控制器绑定:




  •  < bean id =conversionService
    class =org.springframework.context.support.ConversionServiceFactoryBean>
    < property name =converters>
    < set>
    < bean class =somepackage.StringToCategory/>
    < bean class =somepackage.CategoryToString/>
    < / set>
    < / property>
    < / bean>


  • (仅限于Spring 3.1 + ):

      @EnableWebMvc 
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    protected void addFormatters(FormatterRegistry registry){
    registry.addConverter(new StringToCategory());
    registry.addConverter(new CategoryToString());
    }

    }




由于所有这些缺点,为什么要使用Converters?我缺少什么?有没有其他的技巧,我不知道?



我很想继续使用PropertyEditors ...绑定更容易和更快。

解决方案

不,我想你有非常全面地描述PropertyEditor和转换器,一个被声明和注册。在我看来,PropertyEditor的范围是有限的 - 它们有助于将String转换为类型,这个字符串通常来自UI,因此使用@InitBinder注册PropertyEditor,使用WebDataBinder是有道理的。



另一方面,转换器更为通用,它适用于系统中的任何转换 - 而不仅仅是与UI相关的转换(字符串到目标类型)。例如,Spring Integration使用一个转换器广泛地将消息有效载荷转换为所需的类型。



我认为对于UI相关的流PropertyEditor仍然适用于您需要为特定的命令属性做一些自定义的操作。对于其他情况,我将采用Spring引用的建议,并写一个转换器(例如,从Long id转换为实体,作为示例)。


I am looking for the easiest and simplest way to bind and convert data in Spring MVC. If possible, without doing any xml configuration.

So far I've been using PropertyEditors like so :

public class CategoryEditor extends PropertyEditorSupport {

    // Converts a String to a Category (when submitting form)
    @Override
    public void setAsText(String text) {
        Category c = new Category(text);
        this.setValue(c);
    }

    // Converts a Category to a String (when displaying form)
    @Override
    public String getAsText() {
        Category c = (Category) this.getValue();
        return c.getName();
    }

}

and

...
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Category.class, new CategoryEditor());
    }

    ...

}

It is simple : both conversion are defined in the same class, and the binding is straightforward. If I wanted to do a general binding across all my controllers, I could still add 3 lines in my xml config.


But Spring 3.x introduced a new way to do it, using Converters :

So let's say I want to use Converters because it is "the latest alternative". I would have to create two converters :

public class StringToCategory implements Converter<String, Category> {

    @Override
    public Category convert(String source) {
        Category c = new Category(source);
        return c;
    }

}

public class CategoryToString implements Converter<Category, String> {

    @Override
    public String convert(Category source) {
        return source.getName();
    }

}

First drawback : I have to make two classes. Benefit : no need to cast thanks to genericity.

Then, how do I simply data bind the converters ?

Second drawback : I haven't found any simple way (annotations or other programmatic facilities) to do it in a controller : nothing like someSpringObject.registerCustomConverter(...);.

The only ways I've found would be tedious, not simple, and only about general cross-controller binding :

  • XML config :

    <bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="somepackage.StringToCategory"/>
                <bean class="somepackage.CategoryToString"/>
            </set>
        </property>
    </bean>
    

  • Java config (only in Spring 3.1+) :

    @EnableWebMvc
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        protected void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new StringToCategory());
            registry.addConverter(new CategoryToString());
        }
    
    }
    

With all these drawbacks, why using Converters ? Am I missing something ? Are there other tricks that I am not aware of ?

I am tempted to go on using PropertyEditors... Binding is much easier and quicker.

解决方案

No, I think you have very comprehensively described both PropertyEditor and Converter, how each one is declared and registered.

In my mind, PropertyEditors are limited in scope - they help convert String to a type, and this string typically comes from UI, and so registering a PropertyEditor using @InitBinder and using WebDataBinder makes sense.

Converter on the other hand is more generic, it is intended for ANY conversion in the system - not just for UI related conversions(String to target type). For eg, Spring Integration uses a converter extensively for converting a message payload to a desired type.

I think for UI related flows PropertyEditors are still appropriate especially for the case where you need to do something custom for a specific command property. For other cases, I would take the recommendation from Spring reference and write a converter instead(for eg, to convert from a Long id to an entity say, as a sample).

这篇关于Spring MVC类型转换:PropertyEditor或Converter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:14