我有以下课程:
public class CacheModule extends AbstractModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named(TIMEOUT")).to(60);
// ...etc.
}
}
public class DefaultCacheAdaptor implements CacheAdaptor {
private CacheModule bootstrapper = new CacheModule();
@Named("TIMEOUT") private int timeout;
// other fields omitted for brevity
public DefaultCacheAdaptor() {
super();
Injector injector = Guice.createInjector(bootstrapper);
@Named("TIMEOUT") int t = injector.getInstance(Integer.class);
setTimeout(t);
}
}
public class QueueModule extennds AbstractModule {
@Override
public void configure() {
bind(CacheAdaptor.class).to(DefaultCacheAdaptor.class);
}
}
public class DefaultQueueAdaptor implements QueueAdaptor {
private QueueModule bootstrapper = new QueueModule();
private CacheAdaptor cacheAdaptor;
public DefaultQueueAdaptor() {
super();
Injector injector = Guice.createInjector(bootstrapper);
setCacheAdaptor(injector.getInstance(CacheAdaptor.class));
}
}
CacheModule
// 与//CacheAdaptor
位于DefaultCacheAdaptor
不同的 JARQueueModule
中QueueAdaptor
,DefaultQueueAdaptor
因此后一个 JAR 在运行时依赖于前一个 JAR(显然)。
以这种方式编码的目的是允许在用户编写时CacheModule
引导/注入整个对象图DefaultCacheAdaptor
:
CacheAdaptor cacheAdaptor = new DefaultCacheAdaptor();
同上QueueAdaptor
。
碰巧的是,QueueAdaptor
被注入了CacheAdaptor
.
但是,DefaultCacheAdaptor
它是自己对象树的“根”,应该始终由CacheModule
.
所以我问:我怎样才能从内部绑定DefaultCacheAdaptor
到,但确保它本身被初始化/引导?CacheAdaptor
QueueModule
DefaultCacheAdaptor
CacheModule
提前致谢!