@RabbitListener @Payload Validation

从版本 2.3.7 开始,现在可以更轻松地添加一个 Validator 来验证 @RabbitListener@RabbitHandler @Payload 参数。现在,你可以直接将验证器添加到注册器本身。

Starting with version 2.3.7, it is now easier to add a Validator to validate @RabbitListener and @RabbitHandler @Payload arguments. Now, you can simply add the validator to the registrar itself.

@Configuration
@EnableRabbit
public class Config implements RabbitListenerConfigurer {
    ...
    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
      registrar.setValidator(new MyValidator());
    }
}

将 Spring Boot 与验证启动器结合使用时,将自动配置 LocalValidatorFactoryBean

When using Spring Boot with the validation starter, a LocalValidatorFactoryBean is auto-configured:

@Configuration
@EnableRabbit
public class Config implements RabbitListenerConfigurer {
    @Autowired
    private LocalValidatorFactoryBean validator;
    ...
    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
      registrar.setValidator(this.validator);
    }
}

要验证:

To validate:

public static class ValidatedClass {
  @Max(10)
  private int bar;
  public int getBar() {
    return this.bar;
  }
  public void setBar(int bar) {
    this.bar = bar;
  }
}

and

@RabbitListener(id="validated", queues = "queue1", errorHandler = "validationErrorHandler",
      containerFactory = "jsonListenerContainerFactory")
public void validatedListener(@Payload @Valid ValidatedClass val) {
    ...
}
@Bean
public RabbitListenerErrorHandler validationErrorHandler() {
    return (m, e) -> {
        ...
    };
}