@RabbitListener @Payload Validation
从版本 2.3.7 开始,现在可以更轻松地添加一个 Validator
来验证 @RabbitListener
和 @RabbitHandler
@Payload
参数。现在,你可以直接将验证器添加到注册器本身。
@Configuration
@EnableRabbit
public class Config implements RabbitListenerConfigurer {
...
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
registrar.setValidator(new MyValidator());
}
}
将 Spring Boot 与验证启动器结合使用时,将自动配置 |
@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) -> {
...
};
}