http://stackoverflow.com/questions/12544479/spring-mvc-type-conversion-propertyeditor-or-converter
PropertyEditor Converter是spring 使用的两种对象转换方式
统一配置时,实现 WebBindingInitializer 接口:
converter方式
[xml]
ctx.getBea("conversionService")取到对象,ctx.getBea("&conversionService")取到factorybean.
[java]
实现ConditionalGenericConverter 接口可以处理很多相似转换,类亿DomainClassConverter
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
本文介绍了如何在Spring MVC中实现自定义类型转换器(Converter)和编辑器(PropertyEditor),具体包括Category类的转换过程,以及如何在初始化绑定时注册这些自定义组件。此外,文章还探讨了使用统一配置和实现WebBindingInitializer接口的方法来简化自定义转换过程。同时,还展示了如何通过实现ConditionalGenericConverter接口来处理更多相似的转换需求。
247

被折叠的 条评论
为什么被折叠?



