例如我们需要绑定从 JNDI 得到的对象。我们可以仿照下面的代码实现一个可复用的定制的提供者。注意我们注入了 JNDI Context:
package mypackage;
import com.google.inject.*;
import javax.naming.*;
class JndiProvider implements Provider {
@Inject Context context;
final String name;
final Class type;
JndiProvider(Class 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 Provider fromJndi(
Class type, String name) {
return new JndiProvider(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, "..."));
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/13270562/viewspace-217873/
,如需转载,请注明出处,否则将追究法律责任。