`
digfog
  • 浏览: 43617 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[转]Spring MVC type conversion : PropertyEditor or Converter?

 
阅读更多
http://stackoverflow.com/questions/12544479/spring-mvc-type-conversion-propertyeditor-or-converter
PropertyEditor Converter是spring 使用的两种对象转换方式
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();
    }

}

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Category.class, new CategoryEditor());
        binder.setConversionService(conversionService);//conversionService也可以在这注册
    }

统一配置时,实现 WebBindingInitializer 接口:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="cacheSeconds" value="0" />
    <property name="webBindingInitializer">
        <bean class="org.springframework.samples.petclinic.web.ClinicBindingInitializer" />
    </property>
</bean>


converter方式
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();
    }

}

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

ctx.getBea("conversionService")取到对象,ctx.getBea("&conversionService")取到factorybean.

[java]
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

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

}


实现ConditionalGenericConverter 接口可以处理很多相似转换,类亿DomainClassConverter
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics