001/*
002 * Copyright 2002-2015 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.validation.beanvalidation;
018
019import javax.validation.ConstraintValidator;
020import javax.validation.ConstraintValidatorFactory;
021
022import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
023import org.springframework.util.Assert;
024
025/**
026 * JSR-303 {@link ConstraintValidatorFactory} implementation that delegates to a
027 * Spring BeanFactory for creating autowired {@link ConstraintValidator} instances.
028 *
029 * <p>Note that this class is meant for programmatic use, not for declarative use
030 * in a standard {@code validation.xml} file. Consider
031 * {@link org.springframework.web.bind.support.SpringWebConstraintValidatorFactory}
032 * for declarative use in a web application, e.g. with JAX-RS or JAX-WS.
033 *
034 * @author Juergen Hoeller
035 * @since 3.0
036 * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean(Class)
037 * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
038 */
039public class SpringConstraintValidatorFactory implements ConstraintValidatorFactory {
040
041        private final AutowireCapableBeanFactory beanFactory;
042
043
044        /**
045         * Create a new SpringConstraintValidatorFactory for the given BeanFactory.
046         * @param beanFactory the target BeanFactory
047         */
048        public SpringConstraintValidatorFactory(AutowireCapableBeanFactory beanFactory) {
049                Assert.notNull(beanFactory, "BeanFactory must not be null");
050                this.beanFactory = beanFactory;
051        }
052
053
054        @Override
055        public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
056                return this.beanFactory.createBean(key);
057        }
058
059        // Bean Validation 1.1 releaseInstance method
060        public void releaseInstance(ConstraintValidator<?, ?> instance) {
061                this.beanFactory.destroyBean(instance);
062        }
063
064}