View Javadoc

1   /*
2    * Copyright 2007-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.springbyexample.bean.scope.thread;
18  
19  import java.util.Map;
20  
21  import org.springframework.beans.factory.ObjectFactory;
22  import org.springframework.beans.factory.config.Scope;
23  
24  /**
25   * Thread scope implementation.
26   * 
27   * @author David Winterfeldt
28   */
29  public class ThreadScope implements Scope {
30  
31      /**
32       * Gets bean from scope.
33       */
34      public Object get(String name, ObjectFactory<?> factory) {
35          Object result = null;
36          
37          Map<String, Object> hBeans = ThreadScopeContextHolder.currentThreadScopeAttributes().getBeanMap();
38          
39          if (!hBeans.containsKey(name)) {
40              result = factory.getObject();
41              
42              hBeans.put(name, result);
43          } else {
44              result = hBeans.get(name);
45          }
46          
47          
48          return result;
49      }
50      
51      /**
52       * Removes bean from scope.
53       */
54      public Object remove(String name) {
55          Object result = null;
56          
57          Map<String, Object> hBeans = ThreadScopeContextHolder.currentThreadScopeAttributes().getBeanMap();
58  
59          if (hBeans.containsKey(name)) {
60              result = hBeans.get(name);
61              
62              hBeans.remove(name);
63          }
64  
65          return result;
66      }
67  
68      public void registerDestructionCallback(String name, Runnable callback) {
69          ThreadScopeContextHolder.currentThreadScopeAttributes().registerRequestDestructionCallback(name, callback);
70      }
71  
72      /**
73       * Resolve the contextual object for the given key, if any.
74       * Which in this case will always be <code>null</code>.
75       */
76      public Object resolveContextualObject(String key) {
77          return null;
78      }
79  
80      /**
81       * Gets current thread name as the conversation id.
82       */
83      public String getConversationId() {
84          return Thread.currentThread().getName();
85      }
86  
87  }