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.context.access;
18:
19: import org.springframework.beans.factory.BeanFactory;
20: import org.springframework.beans.factory.access.BeanFactoryReference;
21: import org.springframework.context.ApplicationContext;
22: import org.springframework.context.ConfigurableApplicationContext;
23:
24: /**
25: * ApplicationContext-specific implementation of BeanFactoryReference,
26: * wrapping a newly created ApplicationContext, closing it on release.
27: *
28: * <p>As per BeanFactoryReference contract, <code>release</code> may be called
29: * more than once, with subsequent calls not doing anything. However, calling
30: * <code>getFactory</code> after a <code>release</code> call will cause an exception.
31: *
32: * @author Juergen Hoeller
33: * @author Colin Sampaleanu
34: * @since 13.02.2004
35: * @see org.springframework.context.ConfigurableApplicationContext#close
36: */
37: public class ContextBeanFactoryReference implements
38: BeanFactoryReference {
39:
40: private ApplicationContext applicationContext;
41:
42: /**
43: * Create a new ContextBeanFactoryReference for the given context.
44: * @param applicationContext the ApplicationContext to wrap
45: */
46: public ContextBeanFactoryReference(
47: ApplicationContext applicationContext) {
48: this .applicationContext = applicationContext;
49: }
50:
51: public BeanFactory getFactory() {
52: if (this .applicationContext == null) {
53: throw new IllegalStateException(
54: "ApplicationContext owned by this BeanFactoryReference has been released");
55: }
56: return this .applicationContext;
57: }
58:
59: public void release() {
60: if (this .applicationContext != null) {
61: ApplicationContext savedCtx;
62:
63: // We don't actually guarantee thread-safety, but it's not a lot of extra work.
64: synchronized (this ) {
65: savedCtx = this .applicationContext;
66: this .applicationContext = null;
67: }
68:
69: if (savedCtx != null
70: && savedCtx instanceof ConfigurableApplicationContext) {
71: ((ConfigurableApplicationContext) savedCtx).close();
72: }
73: }
74: }
75:
76: }
|