我正在尋找在MVC中綁定和轉換數據的最簡單最簡單的方法。如果可能的話,不用做任何xml配置。Spring MVC類型轉換:PropertyEditor或Converter?
到目前爲止,我一直在使用PropertyEditors像這樣:
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();
}
}
和
...
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Category.class, new CategoryEditor());
}
...
}
它很簡單:兩個轉換都在同一個類中定義,並且綁定是直截了當的。如果我想對所有控制器進行通用綁定,我仍然可以添加3 lines in my xml config。
但春天3.x中引入了一個新的方式來做到這一點,利用Converters:
在Spring容器中,該系統可以作爲一種替代 到屬性編輯器
所以我們假設我想使用轉換器,因爲它是「最新的替代品」。我會創造轉換器:
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();
}
}
第一個缺點:我得把兩個班。好處:不需要感謝通用性。
那麼,我該如何簡單綁定數據轉換器?
第二個缺點:我還沒有找到任何簡單的方法(註解或其他程序設施)做它的控制單元,完全不像。
我發現是乏味的,而不是簡單,只有一般的跨控制器綁定的唯一途徑:
-
<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(只在春季3.1+):
@EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override protected void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToCategory()); registry.addConverter(new CategoryToString()); } }
所有這些缺點,爲什麼使用轉換器?我錯過了什麼嗎?有沒有其他的技巧,我不知道?
我很想繼續使用屬性編輯器...綁定更容易,更快。
注(我偶然也使用Spring 3.2.17):當使用 有需要實際參考本conversionService豆: –
mauhiz