Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

java - Ensure Module Is Loaded Only Once In Guice

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

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.

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?

Update:

It seams Guice is unable to provide the following feature:

  1. Check if a given module was already loaded.
  2. Check if a given class was already bound.
  3. Use Providers within the configuration to be able to do distributed configuration (modules being able to configure objects being contributed).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...