以下是我的控制器的代码段:
@RestController
@RequestMapping(Constants.REST_CONTROLLER_ENDPOINT)
class ProductRestController {
private final ProductValidator productValidator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(productValidator);
}
private Product createProductFromJson(Product input) {
...
return product;
}
@PasswordFilter
@RequestMapping(consumes = { Constants.HAL_CONTENT_TYPE,
Constants.JSON_CONTENT_TYPE }, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Product> createProduct(@RequestBody @Validated Product input) {
Product product = createProductFromJson(input);
Product savedProduct = productRepository.save(product);
return new ResponseEntity<>(product, responseHeaders, HttpStatus.CREATED);
}
@PasswordFilter
@PreAuthorize("@productRestController.validatePermission(authentication, #product)")
@RequestMapping(value = "/{id}", consumes = { Constants.JSON_CONTENT_TYPE }, method = {
RequestMethod.PUT })
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Product> updateProduct(Principal principal, @PathVariable Long id,
@RequestBody @Validated Product product) {
...
return new ResponseEntity<>(updatedProduct, HttpStatus.OK);
}
未在createProduct方法中调用@Validated
。
如果我对@PreAuthorize
发表评论,则会在createProduct方法中调用@Validated
。注释甚至不在createProduct方法上,所以我不确定这是否与@InitBinder
有关。
这是一个SpringBoot 1.4.1应用程序。我正在使用mockmvc @SpringBootTest
来测试此方法
答案 0 :(得分:0)
事实证明,@InitBinder
方法需要公开才能调用验证:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(productValidator);
}