我有我的 RequestParam,我需要驗證它,但是 mu 自定義驗證不適用,我的控制器@RestController@Validatedclass 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); }}和自定義驗證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)); } }
2 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
需要在我的@interface CustomValidation
. 這意味著驗證也可以用于參數。
@Target({ ElementType.PARAMETER })

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
在配置中啟用參數驗證:
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
添加回答
舉報
0/150
提交
取消