Guice指南-与 JNDI 集成
上一篇 /
下一篇 2008-03-26 02:11:03
/ 个人分类:Guice
例如我们需要绑定从 JNDI 得到的对象。我们可以仿照下面的代码实现一个可复用的定制的提供者。注意我们注入了 JNDIContext:
package mypackage;
import com.google.inject.*;
import javax.naming.*;
class JndiProvider<T> implements Provider<T> {
@Inject Context context;
final String name;
final Class<T> type;
JndiProvider(Class<T> type, String name) {
this.name = name;
this.type = type;
}
public T get() {
try {
return type.cast(context.lookup(name));
}
catch (NamingException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a JNDI provider for the given
* type and name.
*/
static <T> Provider<T> fromJndi(
Class<T> type, String name) {
return new JndiProvider<T>(type, name);
}
}
感谢泛型擦除(generic type erasure)技术。我们必须在运行时将依赖传入类中。你可以省略这一步,但在今后跟踪类型转换错误会比较棘手(当 JNDI 返回错误类型的对象的时候)。
我们可以使用定制的JndiProvider来将DataSource绑定到来自 JNDI 的一个对象:
import com.google.inject.*;
import static mypackage.JndiProvider.fromJndi;
import javax.naming.*;
import javax.sql.DataSource;
...
// Bind Context to the default InitialContext.
bind(Context.class).to(InitialContext.class);
// Bind to DataSource from JNDI.
bind(DataSource.class)
.toProvider(fromJndi(DataSource.class, "..."));
导入论坛
引用链接
收藏
分享给好友
推荐到圈子
管理
举报
TAG: