2

I have my RequestParam and I need to validate it, but mu custom validation don't apply, my controller

@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));
        }
    }
Romil Patel
  • 12,879
  • 7
  • 47
  • 76
qwerty
  • 123
  • 9

2 Answers2

5

need to put an annotation in my @interface CustomValidation. This means that validation can also be used on the parameter.

@Target({ ElementType.PARAMETER })
qwerty
  • 123
  • 9
1

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;
}
becher henchiri
  • 618
  • 4
  • 10