我在Spring應用程序中遵循這個方案。ConversionService in Spring
- 請求被髮送到服務器與該對象的ID和其他一些PARAMS在此對象
- 與此ID的對象中填充從數據庫加載
- getter和setter在調用這個對象來填充值
- ,則對象存儲
我問this other question什麼之前,向得到目標物填充請求的PARAMS的最佳途徑。答案是最好的方法是使用conversion service而不是在@ModelAtribute註釋方法中使用它,或者在initBinder中使用編輯器。
所以我試圖使用一個轉換器,但我還沒有找到一個類似的例子,我有點卡住了。我寫了如下所示的代碼:在init binder中,我註冊了轉換服務。因此,在填充User對象上的值之前,將調用convert()方法以從數據庫加載對象。問題是這個配置不起作用,因爲它將對象用戶的id(用戶名字段)轉換爲Object用戶,但是隨後它試圖用對象創建一個setUsername(),所以我得到一個「java.lang .IllegalArgumentException:參數類型不匹配「。
任何人都可以給我一個線索或使用ConversionService獲取所需行爲的方式示例嗎?
謝謝。
@Autowired
private ConversionService conversionService;
@InitBinder("user")
public void initBinder(@RequestParam("username")String username, WebDataBinder binder){
binder.setConversionService(conversionService);
}
@RequestMapping(value="/user/save", method=RequestMethod.POST)
public String save(@ModelAttribute("user") User user, Model model) {
...
}
的東西,如:
@Component
public class UserConversionService implements ConversionService{
...
@Override
public Object convert(Object name, TypeDescriptor arg1, TypeDescriptor arg2) {
return userService.find((String)name);
}
}
另請參見:http://stackoverflow.com/a/10240927/59087 – 2015-02-10 20:24:38