这是我的测试用例,它抛出了预期的org.springframework.batch.item.validator.ValidationException。下面的评论员帮助了http://springbatchbyexample.blogspot.com/2014/09/validation-input-data.html
@Autowired
MdwValidatingItemProcessor mdwValidatingItemProcessor;
@Test(expected = ValidationException.class)
public void notNullOnProperty(){
MecMdw mecMdw = new MecMdw();
//nothing set, property "lob" is null
mdwValidatingItemProcessor.process(mecMdw);
}
我有以下使用javax.validation.constraints.NotNull的域对象:
import javax.validation.constraints.NotNull;
public class MecMdw {
@NotNull
private String lob;
Spring和Spring Batch的版本是:
<spring.version>4.1.7.RELEASE</spring.version>
<spring.batch.version>3.0.4.RELEASE</spring.batch.version>
我在pom.xml中添加了以下库:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
在我的Spring Batch作业XML中,我已经连接了验证器:
<bean id="mdwValidatingItemProcessor" class="com.my.itemprocessor.MdwValidatingItemProcessor">
<property name="validator">
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</property>
</bean>
MdwValidatingItemProcessor看起来如下,对于这个测试用例,我可以在调试时进入process方法:
public class MdwValidatingItemProcessor implements ItemProcessor<MecMdw, MecMdw> {
private Validator validator;
public void setValidator(Validator validator) {
this.validator = validator;
}
@Override
public MecMdw process(MecMdw item) throws Exception {
BindingResult results = BindAndValidate(item);
if (results.hasErrors())
buildValidationException(results);
//TODO write to kickout table
return item;
}
private BindingResult BindAndValidate(MecMdw item) {
DataBinder binder = new DataBinder(item);
binder.setValidator(validator);
binder.validate();
return binder.getBindingResult();
}
private void buildValidationException(BindingResult results) {
StringBuilder msg = new StringBuilder();
for (ObjectError error : results.getAllErrors()) {
msg.append("-*-*-*- \n" + error.toString() + "-*-*-*- \n");
}
throw new ValidationException(msg.toString());
}
这是来自http://springbatchbyexample.blogspot.com/2014/09/validation-input-data.html
的宫廷