KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > example > JndiProvider


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.example;
18
19 import com.google.inject.Inject;
20 import com.google.inject.Provider;
21 import javax.naming.Context JavaDoc;
22 import javax.naming.NamingException JavaDoc;
23
24 class JndiProvider<T> implements Provider<T> {
25
26   @Inject Context JavaDoc context;
27   final String JavaDoc name;
28   final Class JavaDoc<T> type;
29
30   JndiProvider(Class JavaDoc<T> type, String JavaDoc name) {
31     this.name = name;
32     this.type = type;
33   }
34
35   public T get() {
36     try {
37       return type.cast(context.lookup(name));
38     }
39     catch (NamingException JavaDoc e) {
40       throw new RuntimeException JavaDoc(e);
41     }
42   }
43
44   /**
45    * Creates a JNDI provider for the given
46    * type and name.
47    */

48   static <T> Provider<T> fromJndi(
49       Class JavaDoc<T> type, String JavaDoc name) {
50     return new JndiProvider<T>(type, name);
51   }
52 }
53
Popular Tags