其他分享
首页 > 其他分享> > 春季-触发“ beforeSave” RepositoryEventHandler之前的实体验证

春季-触发“ beforeSave” RepositoryEventHandler之前的实体验证

作者:互联网

Spring Data REST docs描述了在RepositoryEventHandler触发后验证实体的方法:

you simply need to register an instance of your validator with the
bean whose job it is to invoke validators after the correct event

在将实体传递给“ beforeSave” RepositoryEventHandlers之前,是否有方法对其应用[声明性] JSR-303验证?

从到目前为止我所看到的调试情况来看,情况并非如此,并且在进行任何验证之前都会触发“ beforeSave” RepositoryEventHandlers.

我可以直接在处理程序中编写验证调用,但这与处理“之后”验证的方式有所不同.

顺便说一句.在Spring Boot 1.3.8和1.5.1之间,事件处理程序调用的顺序似乎已更改.过去,验证发生在@HandleBeforeSave处理程序之前.在1.5.1中,在@HandleBeforeSave处理程序之后触发ValidatingRepositoryEventListener.

更新:

如评论中所述,Spring Data REST Jira中似乎有一个ticket对此已开放.

解决方法:

解决方法:

>创建PreflightValidatingRepositoryEventListener,它扩展了ValidatingRepositoryEventListener并使用@Order(Ordered.HIGHEST_PRECEDENCE)对其进行注释.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class PreflightValidatingRepositoryEventListener extends ValidatingRepositoryEventListener {
    public PreflightValidatingRepositoryEventListener(ObjectFactory<PersistentEntities> persistentEntitiesFactory) {
        super(persistentEntitiesFactory);
    }
}

>添加与ValidatingRepositoryEventListener相同的验证器

@Configuration
@Import(RepositoryRestMvcConfiguration.class)
public class Config extends RepositoryRestConfigurerAdapter {

    @Bean
    @Primary
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }

    @Autowired
    private PreflightValidatingRepositoryEventListener preflightValidatingRepositoryEventListener;

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        Validator validator = validator();

        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);

        preflightValidatingRepositoryEventListener.addValidator("beforeCreate", validator);
        preflightValidatingRepositoryEventListener.addValidator("beforeSave", validator);
    }
}

NOTE: Validation will be ran twice

标签:validation,spring-data-rest,spring
来源: https://codeday.me/bug/20191026/1934727.html