001/*
002 * Copyright 2018-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.validator;
018
019import javax.validation.Validator;
020
021import org.springframework.util.Assert;
022import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
023import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
024
025/**
026 * A {@link ValidatingItemProcessor} that uses the Bean Validation API (JSR-303)
027 * to validate items.
028 *
029 * @param <T> type of items to validate
030 * @author Mahmoud Ben Hassine
031 * @since 4.1
032 */
033public class BeanValidatingItemProcessor<T> extends ValidatingItemProcessor<T> {
034
035        private Validator validator;
036
037        /**
038         * Create a new instance of {@link BeanValidatingItemProcessor} with the
039         * default configuration.
040         */
041        public BeanValidatingItemProcessor() {
042                LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
043                localValidatorFactoryBean.afterPropertiesSet();
044                this.validator = localValidatorFactoryBean.getValidator();
045        }
046
047        /**
048         * Create a new instance of {@link BeanValidatingItemProcessor}.
049         * @param localValidatorFactoryBean used to configure the Bean Validation validator
050         */
051        public BeanValidatingItemProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) {
052                Assert.notNull(localValidatorFactoryBean, "localValidatorFactoryBean must not be null");
053                this.validator = localValidatorFactoryBean.getValidator();
054        }
055
056        @Override
057        public void afterPropertiesSet() throws Exception {
058                SpringValidatorAdapter springValidatorAdapter = new SpringValidatorAdapter(this.validator);
059                SpringValidator<T> springValidator = new SpringValidator<>();
060                springValidator.setValidator(springValidatorAdapter);
061                springValidator.afterPropertiesSet();
062                setValidator(springValidator);
063                super.afterPropertiesSet();
064        }
065}