问题
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