ConfigurationPostProcessorTests.java 5.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
16
package org.springframework.context.annotation;
17 18 19 20 21 22 23 24 25 26 27 28 29

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.*;

import java.lang.reflect.Field;
import java.util.Vector;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
30
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
import org.springframework.util.ClassUtils;


/**
 * Unit tests for {@link ConfigurationClassPostProcessor}.
 *
 * @author Chris Beams
 */
public class ConfigurationPostProcessorTests {

	private static final String ORIG_CGLIB_TEST_CLASS = ConfigurationClassPostProcessor.CGLIB_TEST_CLASS;
	private static final String BOGUS_CGLIB_TEST_CLASS = "a.bogus.class";

	/**
	 * CGLIB is an optional dependency for Spring.  If users attempt
	 * to use {@link Configuration} classes, they'll need it on the classpath;
	 * if Configuration classes are present in the bean factory and CGLIB
	 * is not present, an instructive exception should be thrown.
	 */
	@Test
	public void testFailFastIfCglibNotPresent() {
		@Configuration class Config { }

		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		factory.registerBeanDefinition("config", rootBeanDefinition(Config.class).getBeanDefinition());
		ConfigurationClassPostProcessor cpp = new ConfigurationClassPostProcessor();

		// temporarily set the cglib test class to something bogus
		ConfigurationClassPostProcessor.CGLIB_TEST_CLASS = BOGUS_CGLIB_TEST_CLASS;

		try {
			cpp.postProcessBeanFactory(factory);
		} catch (RuntimeException ex) {
			assertTrue(ex.getMessage().contains("CGLIB is required to process @Configuration classes"));
		} finally {
			ConfigurationClassPostProcessor.CGLIB_TEST_CLASS = ORIG_CGLIB_TEST_CLASS;
		}
	}

	/**
	 * In order to keep Spring's footprint as small as possible, CGLIB must
	 * not be required on the classpath unless the user is taking advantage
	 * of {@link Configuration} classes.
	 * 
	 * This test will fail if any CGLIB classes are classloaded before the call
	 * to {@link ConfigurationClassPostProcessor#enhanceConfigurationClasses}
	 */
	@Ignore @Test // because classloader hacking below causes extremely hard to
	              // debug downstream side effects. Re-enable at will to verify
	              // CGLIB is not prematurely classloaded, but this technique is
	              // not stable enough to leave enabled.
	public void testCglibClassesAreLoadedJustInTimeForEnhancement() throws Exception {
		ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
		Field classesField = ClassLoader.class.getDeclaredField("classes");
		classesField.setAccessible(true);

		// first, remove any CGLIB classes that may have been loaded by other tests
		@SuppressWarnings("unchecked")
		Vector<Class<?>> classes = (Vector<Class<?>>) classesField.get(classLoader);

		Vector<Class<?>> cglibClassesAlreadyLoaded = new Vector<Class<?>>();
		for(Class<?> loadedClass : classes)
			if(loadedClass.getName().startsWith("net.sf.cglib"))
				cglibClassesAlreadyLoaded.add(loadedClass);

		for(Class<?> cglibClass : cglibClassesAlreadyLoaded)
			classes.remove(cglibClass);

		// now, execute a scenario where everything except enhancement occurs
		// -- no CGLIB classes should get loaded!
		testFailFastIfCglibNotPresent();

		// test to ensure that indeed no CGLIB classes have been loaded
		for(Class<?> loadedClass : classes)
			if(loadedClass.getName().startsWith("net.sf.cglib"))
				fail("CGLIB class should not have been eagerly loaded: " + loadedClass.getName());
	}

	/**
	 * Enhanced {@link Configuration} classes are only necessary for respecting
	 * certain bean semantics, like singleton-scoping, scoped proxies, etc.
	 * 
	 * Technically, {@link ConfigurationClassPostProcessor} could fail to enhance the
	 * registered Configuration classes and many use cases would still work.
	 * Certain cases, however, like inter-bean singleton references would not.
	 * We test for such a case below, and in doing so prove that enhancement is
	 * working.
	 */
	@Test
	public void testEnhancementIsPresentBecauseSingletonSemanticsAreRespected() {
		DefaultListableBeanFactory beanFactory = new  DefaultListableBeanFactory();
		beanFactory.registerBeanDefinition("config",
				rootBeanDefinition(SingletonBeanConfig.class).getBeanDefinition());
		new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
		Foo foo = (Foo) beanFactory.getBean("foo");
		Bar bar = (Bar) beanFactory.getBean("bar");
		assertThat(foo, sameInstance(bar.foo));
	}

	@Configuration
	static class SingletonBeanConfig {
		public @Bean Foo foo() {
			return new Foo();
		}

		public @Bean Bar bar() {
			return new Bar(foo());
		}
	}

	static class Foo { }
	static class Bar {
		final Foo foo;
		public Bar(Foo foo) { this.foo = foo; }
	}
	
}