Implementing Java Bean Validation with annotations in Spring Batch app

你离开我真会死。 提交于 2021-01-29 15:39:16

问题


I'm attempting to implement JSR 308 validation annotations on my Java Bean being used in a Spring Batch app. Spring Batch provides a ValidatingItemProcessor, but I want to validate before I get to the processor step, so I decided to go with the Java annotations.

What I thought I could was add the annotation to a method parameter, and if that parameter didn't validate, the method would never be called. But it's not working that way. Apparently I still have to call Validator.validate() first. Am I correct?

This is an example of my bean, with a custom annotation:

public void setValue(@NullOrDecimal String value) {
    // I don't want to come into this method if "value" isn't a null or a decimal
    if (StringUtils.isNotEmpty(value)) {
        this.value = new BigDecimal(value);
    }
}

Is there any way to do what I'm trying to achieve here?


回答1:


You are correct. An annotation on its own does nothing. You should call some code that will introspect this annotations and do something (validation in your case).

Data validation is a typical use case for an item processor, that's why Spring Batch provides the ValidatingItemProcessor. You can always chain another processor in a CompositeItemProcessor if you want to do some processing on valid items (invalid items will be rejected or filtered and will not continue in the chain).




回答2:


I found this article that described exactly how to achieve my solution. Once I made my POJO a component (which may not have been necessary), Spring began to intercept my methods before the parameters were set. That's what I wanted to achieve.



来源:https://stackoverflow.com/questions/65115090/implementing-java-bean-validation-with-annotations-in-spring-batch-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!