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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值