KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > jndi > JndiIntegration


1 /**
2  * Copyright (C) 2006 Google Inc.
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, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package com.google.inject.jndi;
18
19 import com.google.inject.Provider;
20 import com.google.inject.Inject;
21 import javax.naming.Context JavaDoc;
22 import javax.naming.NamingException JavaDoc;
23
24 /**
25  * Integrates Guice with JNDI. Requires a binding to
26  * {@link javax.naming.Context}.
27  *
28  * @author crazybob@google.com (Bob Lee)
29  */

30 public class JndiIntegration {
31
32   private JndiIntegration() {}
33
34   /**
35    * Creates a provider which looks up objects in JNDI using the given name.
36    * Example usage:
37    *
38    * <pre>
39    * bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:..."));
40    * </pre>
41    */

42   public static <T> Provider<T> fromJndi(Class JavaDoc<T> type, String JavaDoc name) {
43     return new JndiProvider<T>(type, name);
44   }
45
46   static class JndiProvider<T> implements Provider<T> {
47
48     @Inject Context JavaDoc context;
49     final Class JavaDoc<T> type;
50     final String JavaDoc name;
51
52     public JndiProvider(Class JavaDoc<T> type, String JavaDoc name) {
53       this.type = type;
54       this.name = name;
55     }
56
57     public T get() {
58       try {
59         return type.cast(context.lookup(name));
60       }
61       catch (NamingException JavaDoc e) {
62         throw new RuntimeException JavaDoc(e);
63       }
64     }
65   }
66 }
67
Popular Tags