2013-01-31 70 views
0

我一直在嘗試添加自定義消息的驗證錯誤的REST服務管理的Spring MVC在@Controller類。Hibernate驗證器自定義消息密鑰與類名稱和字段名稱

Employee類:

public class Employee { 

    @NotNull 
    @NotEmpty 
    private String company; 
    ... 
} 

我的REST服務:

@ResponseStatus(value = HttpStatus.CREATED) 
@RequestMapping(method = RequestMethod.POST) 
public void add(@RequestBody @Valid Employee employee) { 
    employees.add(employee); 
} 

和驗證錯誤解析

@ResponseStatus(value = HttpStatus.BAD_REQUEST) 
@ExceptionHandler(MethodArgumentNotValidException.class) 
public @ResponseBody 
List<String> validationExceptions(MethodArgumentNotValidException e) { 
    List<String> errors = new ArrayList<String>(); 

    for (FieldError error : e.getBindingResult().getFieldErrors()) { 
     errors.add(error.getDefaultMessage()); 
    } 

    return errors; 
} 

所以我把ValidationMessages.properties根我的類路徑,我無法使用以下密鑰獲取我的自定義消息NotEmpty.employee.company

我知道有很多方法可以通過ResourceBundle和error.getCode()或甚至使用密鑰來做到這一點,但我想要特定消息到特定對象的特定字段。

我也不想這樣做@NotEmpty(message = "NotEmpty.employee.company}")。我想要它最簡單。

我該怎麼辦?

回答

0

您是否嘗試過實現自己的

org.springframework.validation.MessageCodesResolver 

,然後宣佈在配置文件中的實現:

<mvc:annotation-driven message-codes-resolver="org.example.YourMessageCodesResolverImpl"/> 

我給它一個嘗試,看來這人能夠建立像你想要的自定義錯誤代碼:

String[] resolveMessageCodes(String errorCode, String objectName, String field, Class<?> fieldType) 

唯一和impo rtant事情我不知道它是否會覆蓋由休眠驗證器生成的錯誤代碼...

我希望它可以幫助(和工作)。

乾杯,

奇科。