ScopingTests.java 10.8 KB
Newer Older
1
/*
2
 * Copyright 2002-2009 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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.
 */

17
package org.springframework.context.annotation.configuration;
18

19 20 21 22
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
23 24 25
import java.util.HashMap;
import java.util.Map;

26
import org.junit.After;
27
import static org.junit.Assert.*;
28 29
import org.junit.Before;
import org.junit.Test;
30 31 32
import test.beans.ITestBean;
import test.beans.TestBean;

33
import org.springframework.aop.scope.ScopedObject;
34
import org.springframework.beans.factory.ObjectFactory;
35
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
36
import org.springframework.beans.factory.support.RootBeanDefinition;
37 38
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
39
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
40 41
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
42 43 44
import org.springframework.context.support.GenericApplicationContext;

/**
45 46
 * Tests that scopes are properly supported by using a custom Scope implementations
 * and scoped proxy {@link Bean} declarations.
47
 *
48 49
 * @author Costin Leau
 * @author Chris Beams
50 51 52 53 54 55
 */
public class ScopingTests {

	public static String flag = "1";

	private static final String SCOPE = "my scope";
56

57
	private CustomScope customScope;
58

59 60 61 62 63 64 65 66 67 68
	private GenericApplicationContext ctx;

	@Before
	public void setUp() throws Exception {
		customScope = new CustomScope();
		ctx = createContext(customScope, ScopedConfigurationClass.class);
	}

	@After
	public void tearDown() throws Exception {
69 70 71
		if (ctx != null) {
			ctx.close();
		}
72 73 74
		ctx = null;
		customScope = null;
	}
75

76
	private GenericApplicationContext createContext(org.springframework.beans.factory.config.Scope customScope, Class<?> configClass) {
77
		DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
78
		if (customScope != null) {
79
			beanFactory.registerScope(SCOPE, customScope);
80 81
		}
		beanFactory.registerBeanDefinition("config", new RootBeanDefinition(configClass));
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
		GenericApplicationContext ctx = new GenericApplicationContext(beanFactory);
		ctx.addBeanFactoryPostProcessor(new ConfigurationClassPostProcessor());
		ctx.refresh();
		return ctx;
	}

	@Test
	public void testScopeOnClasses() throws Exception {
		genericTestScope("scopedClass");
	}

	@Test
	public void testScopeOnInterfaces() throws Exception {
		genericTestScope("scopedInterface");
	}

	@Test
	public void testSameScopeOnDifferentBeans() throws Exception {
		Object beanAInScope = ctx.getBean("scopedClass");
		Object beanBInScope = ctx.getBean("scopedInterface");

		assertNotSame(beanAInScope, beanBInScope);

		customScope.createNewScope = true;

		Object newBeanAInScope = ctx.getBean("scopedClass");
		Object newBeanBInScope = ctx.getBean("scopedInterface");

		assertNotSame(newBeanAInScope, newBeanBInScope);
		assertNotSame(newBeanAInScope, beanAInScope);
		assertNotSame(newBeanBInScope, beanBInScope);
	}

	@Test
	public void testRawScopes() throws Exception {
		String beanName = "scopedProxyInterface";

		// get hidden bean
		Object bean = ctx.getBean("scopedTarget." + beanName);

		assertFalse(bean instanceof ScopedObject);
	}

	@Test
	public void testScopedProxyConfiguration() throws Exception {
		TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedInterfaceDep");
		ITestBean spouse = singleton.getSpouse();
		assertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);

		String beanName = "scopedProxyInterface";

133
		String scopedBeanName = "scopedTarget." + beanName;
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

		// get hidden bean
		assertEquals(flag, spouse.getName());

		ITestBean spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
		assertEquals(spouse.getName(), spouseFromBF.getName());
		// the scope proxy has kicked in
		assertNotSame(spouse, spouseFromBF);

		// create a new bean
		customScope.createNewScope = true;

		// get the bean again from the BF
		spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
		// make sure the name has been updated
		assertSame(spouse.getName(), spouseFromBF.getName());
		assertNotSame(spouse, spouseFromBF);

		// get the bean again
		spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
		assertSame(spouse.getName(), spouseFromBF.getName());
	}


	@Test
	public void testScopedProxyConfigurationWithClasses() throws Exception {

		TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedClassDep");
		ITestBean spouse = singleton.getSpouse();
		assertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);

		String beanName = "scopedProxyClass";

167
		String scopedBeanName = "scopedTarget." + beanName;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

		// get hidden bean
		assertEquals(flag, spouse.getName());

		TestBean spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
		assertEquals(spouse.getName(), spouseFromBF.getName());
		// the scope proxy has kicked in
		assertNotSame(spouse, spouseFromBF);

		// create a new bean
		customScope.createNewScope = true;
		flag = "boo";

		// get the bean again from the BF
		spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
		// make sure the name has been updated
		assertSame(spouse.getName(), spouseFromBF.getName());
		assertNotSame(spouse, spouseFromBF);

		// get the bean again
		spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
		assertSame(spouse.getName(), spouseFromBF.getName());
	}


	@Test
	public void testScopedConfigurationBeanDefinitionCount() throws Exception {
		// count the beans
C
Chris Beams 已提交
196 197
		// 6 @Beans + 1 Configuration + 2 scoped proxy + 1 importRegistry
		assertEquals(10, ctx.getBeanDefinitionCount());
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	}
	
//	/**
//	 * SJC-254 caught a regression in handling scoped proxies starting in 1.0 m4.
//	 * The ScopedProxyFactoryBean object was having its scope set to that of its delegate
//	 * whereas it should have remained singleton.
//	 */
//	@Test
//	public void sjc254() {
//		JavaConfigWebApplicationContext ctx = new JavaConfigWebApplicationContext();
//		ctx.setConfigLocations(new String[] { ScopeTestConfiguration.class.getName() });
//		ctx.refresh();
//		
//		// should be fine
//		ctx.getBean(Bar.class);
//		
//		boolean threw = false;
//		try {
//			ctx.getBean(Foo.class);
//		} catch (BeanCreationException ex) {
//			if(ex.getCause() instanceof IllegalStateException) {
//				threw = true;
//			}
//		}
//		assertTrue(threw);
//	}
	
	@Configuration
	static class ScopeTestConfiguration {

228
		@Bean
229
		@Scope(value="session", proxyMode=ScopedProxyMode.INTERFACES)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		public Foo foo() {
			return new Foo();
		}

		@Bean
		public Bar bar() {
			return new Bar(foo());
		}
	}
	
	static class Foo {
		public Foo() {
			//System.out.println("created foo: " + this.getClass().getName());
		}
		
		public void doSomething() {
			//System.out.println("interesting: " + this);
		}
	}
	
	static class Bar {
	
		private final Foo foo;
	
		public Bar(Foo foo) {
			this.foo = foo;
			//System.out.println("created bar: " + this);
		}
	
		public Foo getFoo() {
			return foo;
		}
		
	}

	private void genericTestScope(String beanName) throws Exception {
		String message = "scope is ignored";
		Object bean1 = ctx.getBean(beanName);
		Object bean2 = ctx.getBean(beanName);

		assertSame(message, bean1, bean2);

		Object bean3 = ctx.getBean(beanName);

		assertSame(message, bean1, bean3);

		// make the scope create a new object
		customScope.createNewScope = true;

		Object newBean1 = ctx.getBean(beanName);
		assertNotSame(message, bean1, newBean1);

		Object sameBean1 = ctx.getBean(beanName);

		assertSame(message, newBean1, sameBean1);

		// make the scope create a new object
		customScope.createNewScope = true;

		Object newBean2 = ctx.getBean(beanName);
		assertNotSame(message, newBean1, newBean2);

		// make the scope create a new object .. again
		customScope.createNewScope = true;

		Object newBean3 = ctx.getBean(beanName);
		assertNotSame(message, newBean2, newBean3);
	}

	@Configuration
	public static class InvalidProxyOnPredefinedScopesConfiguration {
301

302
		@Bean @Scope(proxyMode=ScopedProxyMode.INTERFACES)
303 304 305 306 307
		public Object invalidProxyOnPredefinedScopes() { return new Object(); }
	}

	@Configuration
	public static class ScopedConfigurationClass {
308

309
		@Bean
310
		@MyScope
311 312 313 314 315 316
		public TestBean scopedClass() {
			TestBean tb = new TestBean();
			tb.setName(flag);
			return tb;
		}

317
		@Bean
318
		@MyScope
319 320 321 322 323 324
		public ITestBean scopedInterface() {
			TestBean tb = new TestBean();
			tb.setName(flag);
			return tb;
		}

J
Juergen Hoeller 已提交
325
		@Bean
326
		@MyProxiedScope
327 328 329 330 331 332
		public ITestBean scopedProxyInterface() {
			TestBean tb = new TestBean();
			tb.setName(flag);
			return tb;
		}

333
		@MyProxiedScope
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
		public TestBean scopedProxyClass() {
			TestBean tb = new TestBean();
			tb.setName(flag);
			return tb;
		}

		@Bean
		public TestBean singletonWithScopedClassDep() {
			TestBean singleton = new TestBean();
			singleton.setSpouse(scopedProxyClass());
			return singleton;
		}

		@Bean
		public TestBean singletonWithScopedInterfaceDep() {
			TestBean singleton = new TestBean();
			singleton.setSpouse(scopedProxyInterface());
			return singleton;
		}
	}

355

356 357 358 359 360 361 362 363 364
	@Target({ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	@Scope(SCOPE)
	@interface MyScope {
	}


	@Target({ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
365
	@Bean
366 367 368 369 370
	@Scope(value=SCOPE, proxyMode=ScopedProxyMode.TARGET_CLASS)
	@interface MyProxiedScope {
	}


371 372 373 374
	/**
	 * Simple scope implementation which creates object based on a flag.
	 * @author Costin Leau
	 * @author Chris Beams
375
	 */
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	static class CustomScope implements org.springframework.beans.factory.config.Scope {

		public boolean createNewScope = true;

		private Map<String, Object> beans = new HashMap<String, Object>();

		public Object get(String name, ObjectFactory<?> objectFactory) {
			if (createNewScope) {
				beans.clear();
				// reset the flag back
				createNewScope = false;
			}

			Object bean = beans.get(name);
			// if a new object is requested or none exists under the current
			// name, create one
			if (bean == null) {
				beans.put(name, objectFactory.getObject());
			}

			return beans.get(name);
397 398
		}

399 400
		public String getConversationId() {
			return null;
401 402
		}

403 404 405
		public void registerDestructionCallback(String name, Runnable callback) {
			// do nothing
		}
406

407 408 409
		public Object remove(String name) {
			return beans.remove(name);
		}
410

411 412 413
		public Object resolveContextualObject(String key) {
			return null;
		}
414 415 416
	}

}