1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springbyexample.web.context;
18
19 import javax.servlet.ServletContext;
20
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.springframework.beans.factory.ObjectFactory;
24 import org.springframework.beans.factory.config.Scope;
25 import org.springframework.util.StringUtils;
26 import org.springframework.web.context.ServletContextAware;
27
28
29
30
31
32
33
34
35 public class ServletContextScope implements Scope, ServletContextAware {
36
37 final Logger logger = LoggerFactory.getLogger(ServletContextScope.class);
38
39 protected ServletContext servletContext = null;
40 protected String context = null;
41
42
43
44
45 public void setServletContext(ServletContext servletContext) {
46 this.servletContext = servletContext;
47 }
48
49
50
51
52
53
54 public String getContext() {
55 return context;
56 }
57
58
59
60
61
62
63 public void setContext(String context) {
64 this.context = context;
65 }
66
67
68
69
70 public Object get(String name, ObjectFactory factory) {
71 Object result = null;
72
73 ServletContext sc = getServletContext();
74
75 result = sc.getAttribute(name);
76
77 if (result == null) {
78 result = factory.getObject();
79
80 sc.setAttribute(name, result);
81 }
82
83 return result;
84 }
85
86
87
88
89 public Object remove(String name) {
90 Object result = null;
91
92 ServletContext sc = getServletContext();
93
94 result = sc.getAttribute(name);
95
96 sc.removeAttribute(name);
97
98 return result;
99 }
100
101
102
103
104
105
106 public void registerDestructionCallback(String name, Runnable callback) {
107 logger.warn("ServletContextScope does not support descruction callbacks");
108 }
109
110
111
112
113
114 public Object resolveContextualObject(String key) {
115 return null;
116 }
117
118
119
120
121
122
123 public String getConversationId() {
124 return null;
125 }
126
127
128
129
130 protected ServletContext getServletContext() {
131 ServletContext sc = null;
132
133 if (StringUtils.hasText(context)) {
134 sc = servletContext.getContext(context);
135
136 if (sc == null) {
137 throw new UnsupportedOperationException("Unable to get context for '" + context + "'. " +
138 "Server may not have cross context support or may be configured incorrectly.");
139 }
140 } else {
141 sc = servletContext;
142 }
143
144 return sc;
145 }
146
147 }