01: /*
02: * Copyright 2007 Tim Peierls
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: package org.directwebremoting.guice.spring;
17:
18: import com.google.inject.Provider;
19:
20: import java.io.Closeable;
21: import java.io.IOException;
22:
23: import org.apache.commons.logging.LogFactory;
24: import org.apache.commons.logging.Log;
25:
26: import org.springframework.beans.factory.BeanFactory;
27: import org.springframework.beans.factory.DisposableBean;
28:
29: /**
30: * Lazily creates a singleton BeanFactory and, when {@code close()} is
31: * called, destroys it if it exists and is a {@code DisposableBean}.
32: */
33: class CloseableBeanFactoryProvider implements Closeable,
34: Provider<BeanFactory> {
35: CloseableBeanFactoryProvider(BeanFactoryLoader loader) {
36: this .loader = loader;
37: }
38:
39: /* (non-Javadoc)
40: * @see com.google.inject.Provider#get()
41: */
42: public synchronized BeanFactory get() {
43: if (beanFactory == null) {
44: beanFactory = loader.loadBeanFactory();
45: }
46: return beanFactory;
47: }
48:
49: /* (non-Javadoc)
50: * @see java.io.Closeable#close()
51: */
52: public synchronized void close() throws IOException {
53: if (beanFactory != null
54: && beanFactory instanceof DisposableBean) {
55: try {
56: ((DisposableBean) beanFactory).destroy();
57: log.info("Destroyed BeanFactory from Guice provider.");
58: } catch (IOException e) {
59: log.info("Caught IO exception destroying BeanFactory: "
60: + e);
61: throw e;
62: } catch (Exception e) {
63: log
64: .info("Unexpected exception while destroying BeanFactory: "
65: + e);
66: throw new RuntimeException(e);
67: }
68: }
69: }
70:
71: private final BeanFactoryLoader loader;
72:
73: /* @GuardedBy("this") */private BeanFactory beanFactory;
74:
75: /**
76: * The log stream
77: */
78: private static final Log log = LogFactory
79: .getLog(CloseableBeanFactoryProvider.class);
80: }
|