[英]can't apply custom validation to requestParam
I have my RequestParam and I need to validate it, but mu custom validation don't apply, my controller我有我的 RequestParam,我需要验证它,但是 mu 自定义验证不适用,我的控制器
@RestController
@Validated
class ExchangeController {
private static final Logger logger = Logger.getLogger(ExchangeController.class.getName());
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
@Qualifier("dataService")
private CurrencyExchangeService currencyExchangeService;
@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
public Object converting(@RequestParam("fromCurrency") @NotNull @CurrencyValidation String fromCurrency,
@RequestParam("toCurrency") @NotNull String toCurrency,
@RequestParam("amount") @NotNull String amount) throws IOException {
BigDecimal convertedAmount = currencyExchangeService.convert(fromCurrency, toCurrency, new BigDecimal(amount));
return new ExchangeRateDTO(fromCurrency, toCurrency, new BigDecimal(amount), convertedAmount);
}
}
and custom validation和自定义验证
public class ConstractCurrencyValidator implements
ConstraintValidator<CurrencyValidation, String> {
@Override
public void initialize(CurrencyValidation currency) {
}
@Override
public boolean isValid(String currency, ConstraintValidatorContext constraintValidatorContext) {
return currency != null && Currency.getAvailableCurrencies().contains(Currency.getInstance(currency));
}
}
need to put an annotation in my @interface CustomValidation
.需要在我的@interface CustomValidation
注释。 This means that validation can also be used on the parameter.这意味着验证也可以用于参数。
@Target({ ElementType.PARAMETER })
Enable parameter validation in config:在配置中启用参数验证:
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.