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.web.bind.support; 018 019import javax.validation.ConstraintValidator; 020import javax.validation.ConstraintValidatorFactory; 021 022import org.springframework.web.context.ContextLoader; 023import org.springframework.web.context.WebApplicationContext; 024 025/** 026 * JSR-303 {@link ConstraintValidatorFactory} implementation that delegates to 027 * the current Spring {@link WebApplicationContext} for creating autowired 028 * {@link ConstraintValidator} instances. 029 * 030 * <p>In contrast to 031 * {@link org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory}, 032 * this variant is meant for declarative use in a standard {@code validation.xml} file, 033 * e.g. in combination with JAX-RS or JAX-WS. 034 * 035 * @author Juergen Hoeller 036 * @since 4.2.1 037 * @see ContextLoader#getCurrentWebApplicationContext() 038 * @see org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory 039 */ 040public class SpringWebConstraintValidatorFactory implements ConstraintValidatorFactory { 041 042 @Override 043 public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { 044 return getWebApplicationContext().getAutowireCapableBeanFactory().createBean(key); 045 } 046 047 // Bean Validation 1.1 releaseInstance method 048 public void releaseInstance(ConstraintValidator<?, ?> instance) { 049 getWebApplicationContext().getAutowireCapableBeanFactory().destroyBean(instance); 050 } 051 052 053 /** 054 * Retrieve the Spring {@link WebApplicationContext} to use. 055 * The default implementation returns the current {@link WebApplicationContext} 056 * as registered for the thread context class loader. 057 * @return the current WebApplicationContext (never {@code null}) 058 * @see ContextLoader#getCurrentWebApplicationContext() 059 */ 060 protected WebApplicationContext getWebApplicationContext() { 061 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); 062 if (wac == null) { 063 throw new IllegalStateException("No WebApplicationContext registered for current thread - " + 064 "consider overriding SpringWebConstraintValidatorFactory.getWebApplicationContext()"); 065 } 066 return wac; 067 } 068 069}