确保模块仅在Guice中加载一次 [英] Ensure Module Is Loaded Only Once In Guice

查看:110
本文介绍了确保模块仅在Guice中加载一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须处理Guice,我想知道如何处理模块中的依赖关系。

Having to deal with Guice, I wonder how I should handle dependencies in terms of modules.

在Guice中,每个模块都由一个实例提供。因此,如果我有一个需要某个服务的模块,它会创建一个模块,为该服务添加一个绑定并安装它(binder.install(module))。

In Guice every module is provided by an instance. So if I have a module requiring a certain service it creates the module adding a binding to that service and installs it (binder.install(module)).

现在我有了两个独立的模块,完全可以独立使用,并且都安装相同的数据库模块。

Now I have two independent modules that make completely sense to be used independently and both install the same database module.

独立使用这两个模块没有问题,但如果两个模块在同一个应用程序中使用会发生什么?数据库模块将由两个模块独立加载,但不能正确。

Using both modules independently no problem arise but what happens if both modules are used in the same application? The database module will be loaded by both modules independently and that can not be correct.

有没有办法向绑定器询问某个类型是否已经绑定?我无法使用getProvider来检查它,因为所有返回的都是LookupProvider,无论某些东西是否已经绑定。

Is there a way to ask the binder if a certain type has already a binding? I can not use getProvider to check on that since all that is returned is a LookupProvider regardless if something is already bind or not.

那么如何处理这种情况?

So how one has to deal with this scenario?

更新:

它接缝Guice无法提供以下功能:

It seams Guice is unable to provide the following feature:


  1. 检查是否已加载给定模块。

  2. 检查给定的类是否已绑定。

  3. 使用配置中的提供商可以进行分布式配置(模块能够配置被提供的对象)。


推荐答案

Guice有两个功能来处理这种情况。第一个是模块重复数据删除。这意味着如果安装两个等效的模块(通过 equals() hashCode()),只有一个 configure()方法将运行。但是,这个解决方案有些脆弱,因为它无法在SPI转换中存活, Modules.override()等。

Guice has two features to deal with this situation. The first is module de-duplication. This means that if two modules are installed that are equivalent (by equals() and hashCode()), only one's configure() method will run. However, this solution is somewhat brittle because it won't survive SPI transformations, Modules.override(), etc.

第二个和IMO更好的解决方案是绑定重复数据删除。这意味着Guice将接受完全重复的绑定。因此,如果您的模块执行 bind(Interface.class).to(Implementation.class),那么它的 configure()<无关紧要/ code>方法运行两次,因为Guice将处理重复绑定就好了。

The second, and IMO better solution, is binding de-duplication. This means that Guice will accept bindings that are exact duplicates. So if your module does bind(Interface.class).to(Implementation.class), it doesn't even matter if its configure() method runs twice, because Guice will handle the duplicate binding just fine.

这篇关于确保模块仅在Guice中加载一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆