为了账号安全,请及时绑定邮箱和手机立即绑定

无法将自定义验证应用于 requestParam

无法将自定义验证应用于 requestParam

红糖糍粑 2023-04-26 16:24:17
我有我的 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 })


查看完整回答
反对 回复 2023-04-26
?
MMTTMM

TA贡献1869条经验 获得超4个赞

在配置中启用参数验证:


 @Bean

public Validator validator() {

    return new LocalValidatorFactoryBean();

}


@Bean

public MethodValidationPostProcessor methodValidationPostProcessor() {

    MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();

    methodValidationPostProcessor.setValidator(validator());

    return methodValidationPostProcessor;

}


查看完整回答
反对 回复 2023-04-26
  • 2 回答
  • 0 关注
  • 122 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信