01: /**
02: * Copyright (C) 2006 Google Inc.
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: */package com.google.inject.jndi;
16:
17: import com.google.inject.Provider;
18: import com.google.inject.Inject;
19: import javax.naming.Context;
20: import javax.naming.NamingException;
21:
22: /**
23: * Integrates Guice with JNDI. Requires a binding to
24: * {@link javax.naming.Context}.
25: *
26: * @author crazybob@google.com (Bob Lee)
27: */
28: public class JndiIntegration {
29:
30: private JndiIntegration() {
31: }
32:
33: /**
34: * Creates a provider which looks up objects in JNDI using the given name.
35: * Example usage:
36: *
37: * <pre>
38: * bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:..."));
39: * </pre>
40: */
41: public static <T> Provider<T> fromJndi(Class<T> type, String name) {
42: return new JndiProvider<T>(type, name);
43: }
44:
45: static class JndiProvider<T> implements Provider<T> {
46:
47: @Inject
48: Context context;
49: final Class<T> type;
50: final String name;
51:
52: public JndiProvider(Class<T> type, String 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: } catch (NamingException e) {
61: throw new RuntimeException(e);
62: }
63: }
64: }
65: }
|