View Javadoc

1   /*
2    * Copyright 2004-2010 the Seasar Foundation and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  
17  package org.seasar.cubby.plugins.guice.spi;
18  
19  import org.seasar.cubby.spi.ContainerProvider;
20  import org.seasar.cubby.spi.container.Container;
21  import org.seasar.cubby.spi.container.LookupException;
22  
23  import com.google.inject.ConfigurationException;
24  import com.google.inject.Inject;
25  import com.google.inject.Injector;
26  
27  /**
28   * Guice の {@link Injector} による {@link Container} の実装を提供します。
29   * 
30   * @author baba
31   */
32  public class GuiceContainerProvider implements ContainerProvider {
33  
34  	/** {@link Container} */
35  	private final Container container;
36  
37  	/**
38  	 * インスタンス化します。
39  	 * 
40  	 * @param injector
41  	 *            インジェクタ
42  	 */
43  	@Inject
44  	public GuiceContainerProvider(final Injector injector) {
45  		this.container = new GuiceContainerImpl(injector);
46  	}
47  
48  	/**
49  	 * {@inheritDoc}
50  	 */
51  	public Container getContainer() {
52  		return container;
53  	}
54  
55  	/**
56  	 * {@link Injector} による {@link Container} の実装です。
57  	 * 
58  	 * @author baba
59  	 */
60  	private static class GuiceContainerImpl implements Container {
61  
62  		/** インスタンスをルックアップするための {@link Injector} */
63  		private final Injector injector;
64  
65  		/**
66  		 * インスタンス化します。
67  		 * 
68  		 * @param injector
69  		 *            インスタンスをルックアップするための {@link Injector}
70  		 */
71  		public GuiceContainerImpl(final Injector injector) {
72  			this.injector = injector;
73  		}
74  
75  		/**
76  		 * {@inheritDoc}
77  		 */
78  		public <T> T lookup(final Class<T> type) throws LookupException {
79  			try {
80  				return injector.getInstance(type);
81  			} catch (final ConfigurationException e) {
82  				throw new LookupException(e);
83  			}
84  		}
85  
86  	}
87  
88  }