View Javadoc
1   /*
2    * Copyright 2002-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.tests.context;
18  
19  import java.io.Serializable;
20  import java.util.HashMap;
21  import java.util.Iterator;
22  import java.util.LinkedList;
23  import java.util.List;
24  import java.util.Map;
25  
26  import org.springframework.beans.factory.ObjectFactory;
27  import org.springframework.beans.factory.config.Scope;
28  
29  /**
30   * @author Juergen Hoeller
31   */
32  @SuppressWarnings("serial")
33  public class SimpleMapScope implements Scope, Serializable {
34  
35  	private final Map<String, Object> map = new HashMap<String, Object>();
36  
37  	private final List<Runnable> callbacks = new LinkedList<Runnable>();
38  
39  
40  	public SimpleMapScope() {
41  	}
42  
43  	public final Map<String, Object> getMap() {
44  		return this.map;
45  	}
46  
47  
48  	@Override
49  	public Object get(String name, ObjectFactory<?> objectFactory) {
50  		synchronized (this.map) {
51  			Object scopedObject = this.map.get(name);
52  			if (scopedObject == null) {
53  				scopedObject = objectFactory.getObject();
54  				this.map.put(name, scopedObject);
55  			}
56  			return scopedObject;
57  		}
58  	}
59  
60  	@Override
61  	public Object remove(String name) {
62  		synchronized (this.map) {
63  			return this.map.remove(name);
64  		}
65  	}
66  
67  	@Override
68  	public void registerDestructionCallback(String name, Runnable callback) {
69  		this.callbacks.add(callback);
70  	}
71  
72  	@Override
73  	public Object resolveContextualObject(String key) {
74  		return null;
75  	}
76  
77  	public void close() {
78  		for (Iterator<Runnable> it = this.callbacks.iterator(); it.hasNext();) {
79  			Runnable runnable = it.next();
80  			runnable.run();
81  		}
82  	}
83  
84  	@Override
85  	public String getConversationId() {
86  		return null;
87  	}
88  
89  }