001/* 002 * Copyright 2002-2014 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.test.context.support; 018 019import org.springframework.beans.BeanUtils; 020import org.springframework.test.context.SmartContextLoader; 021import org.springframework.util.ClassUtils; 022 023/** 024 * {@code DelegatingSmartContextLoader} is a concrete implementation of 025 * {@link AbstractDelegatingSmartContextLoader} that delegates to a 026 * {@link GenericXmlContextLoader} (or a {@link GenericGroovyXmlContextLoader} if Groovy 027 * is present in the classpath) and an {@link AnnotationConfigContextLoader}. 028 * 029 * @author Sam Brannen 030 * @since 3.1 031 * @see SmartContextLoader 032 * @see AbstractDelegatingSmartContextLoader 033 * @see GenericXmlContextLoader 034 * @see GenericGroovyXmlContextLoader 035 * @see AnnotationConfigContextLoader 036 */ 037public class DelegatingSmartContextLoader extends AbstractDelegatingSmartContextLoader { 038 039 private static final String GROOVY_XML_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.GenericGroovyXmlContextLoader"; 040 041 private static final boolean groovyPresent = ClassUtils.isPresent("groovy.lang.Closure", 042 DelegatingSmartContextLoader.class.getClassLoader()) 043 && ClassUtils.isPresent(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, 044 DelegatingSmartContextLoader.class.getClassLoader()); 045 046 private final SmartContextLoader xmlLoader; 047 private final SmartContextLoader annotationConfigLoader; 048 049 050 public DelegatingSmartContextLoader() { 051 if (groovyPresent) { 052 try { 053 Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, 054 DelegatingSmartContextLoader.class.getClassLoader()); 055 this.xmlLoader = (SmartContextLoader) BeanUtils.instantiateClass(loaderClass); 056 } 057 catch (Throwable ex) { 058 throw new IllegalStateException("Failed to enable support for Groovy scripts; " 059 + "could not load class: " + GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, ex); 060 } 061 } 062 else { 063 this.xmlLoader = new GenericXmlContextLoader(); 064 } 065 066 this.annotationConfigLoader = new AnnotationConfigContextLoader(); 067 } 068 069 @Override 070 protected SmartContextLoader getXmlLoader() { 071 return this.xmlLoader; 072 } 073 074 @Override 075 protected SmartContextLoader getAnnotationConfigLoader() { 076 return this.annotationConfigLoader; 077 } 078 079}