01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.web.context.support;
18:
19: import javax.servlet.ServletContext;
20:
21: import org.springframework.beans.factory.FactoryBean;
22: import org.springframework.web.context.ServletContextAware;
23:
24: /**
25: * FactoryBean that fetches a specific, existing ServletContext attribute.
26: * Exposes that ServletContext attribute when used as bean reference,
27: * effectively making it available as named Spring bean instance.
28: *
29: * <p>Intended to link in ServletContext attributes that exist before
30: * the startup of the Spring application context. Typically, such
31: * attributes will have been put there by third-party web frameworks.
32: * In a purely Spring-based web application, no such linking in of
33: * ServletContext attrutes will be necessary.
34: *
35: * @author Juergen Hoeller
36: * @since 1.1.4
37: * @see ServletContextParameterFactoryBean
38: */
39: public class ServletContextAttributeFactoryBean implements FactoryBean,
40: ServletContextAware {
41:
42: private String attributeName;
43:
44: private Object attribute;
45:
46: /**
47: * Set the name of the ServletContext attribute to expose.
48: */
49: public void setAttributeName(String attributeName) {
50: this .attributeName = attributeName;
51: }
52:
53: public void setServletContext(ServletContext servletContext) {
54: if (this .attributeName == null) {
55: throw new IllegalArgumentException(
56: "attributeName is required");
57: }
58: this .attribute = servletContext
59: .getAttribute(this .attributeName);
60: if (this .attribute == null) {
61: throw new IllegalStateException(
62: "No ServletContext attribute '"
63: + this .attributeName + "' found");
64: }
65: }
66:
67: public Object getObject() throws Exception {
68: return this .attribute;
69: }
70:
71: public Class getObjectType() {
72: return (this .attribute != null ? this .attribute.getClass()
73: : null);
74: }
75:
76: public boolean isSingleton() {
77: return true;
78: }
79:
80: }
|