filter java 是单例的吗_java – 实例化每个范围/组单例 – 陷入Guice依赖地狱

在发布后不到一个小时就有点突破的道歉.

我似乎能够通过稍微滥用http://code.google.com/p/google-guice/wiki/CustomScopes提供的线程局部范围实现来解决这个问题.在不使用子注入器的情况下解决此问题似乎是一种有点干净的方法.不过,我不确定它是否“合适”.我还是会接受其他答案.

这就是我做的.首先,我创建一个范围实例,将其绑定到适当的注释,并使其在注入器中可用:

ThreadLocalScope scope = new ThreadLocalScope();

bindScope(ExperimentScoped.class,scope);

bind(ThreadLocalScope.class).toInstance(scope);

然后,正如文档所说,我需要为范围内播种的每种类型的键绑定一个假提供者:

bind(SomeKey.class)

.toProvider(ThreadLocalScope.

我可能还有一些其他可范围的对象,我想在每个范围内区分,所以我也绑定它们.这些是上面的TestClass和RealClass.可能还有使用@ExperimentScoped注释的SomeScopedClass:

bind(InterfaceA.class).to(TestClass.class).in(ExperimentScoped.class);

bind(InterfaceB.class).to(TestClass.class).in(ExperimentScoped.class);

bind(SomeInterface.class).to(SomeScopedClass.class);

最后,我可以使用范围从不同的线程并行创建不同的相互依赖的对象集.每个线程都可以执行类似下面的操作,即使它们使用相同的注入器:

ThreadLocalScope scope = injector.getInstance(ThreadLocalScope.class);

scope.enter();

try {

// Seed the seed-able keys

scope.seed(SomeKey.class,keyInstance);

scope.seed(SomeOtherKey.class,otherKeyInstance);

SomeScopedClass instance = injector.getInstance(SomeScopedClass.class);

// Hooray! instance was injected with the seeds and created just for this scope!

}

finally {

scope.exit(); // Throws away the scope and referenced objects.

}

在我的情况下,我可以完全放弃范围,因为我不关心在正确连接后跟踪范围内的对象集.但是如果我想稍后回到这个范围并注入更多的对象,它可能无法工作.

希望这有助于某人. Guice范围文档太糟糕了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值