@RabbitListener @Payload 验证
从 2.3.7 版本开始,向 @RabbitListener
和 @RabbitHandler
的 @Payload
参数添加 Validator
进行验证变得更加容易。现在,您只需将验证器添加到注册器本身即可。
@Configuration
@EnableRabbit
public class Config implements RabbitListenerConfigurer {
...
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
registrar.setValidator(new MyValidator());
}
}
当使用带有验证启动器的 Spring Boot 时,会自动配置 LocalValidatorFactoryBean 。
|
@Configuration
@EnableRabbit
public class Config implements RabbitListenerConfigurer {
@Autowired
private LocalValidatorFactoryBean validator;
...
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
registrar.setValidator(this.validator);
}
}
要验证
public static class ValidatedClass {
@Max(10)
private int bar;
public int getBar() {
return this.bar;
}
public void setBar(int bar) {
this.bar = bar;
}
}
和
@RabbitListener(id="validated", queues = "queue1", errorHandler = "validationErrorHandler",
containerFactory = "jsonListenerContainerFactory")
public void validatedListener(@Payload @Valid ValidatedClass val) {
...
}
@Bean
public RabbitListenerErrorHandler validationErrorHandler() {
return (m, e) -> {
...
};
}