Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure Module Is Loaded Only Once In Guice

Tags:

java

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).
like image 881
Martin Kersten Avatar asked Dec 22 '13 23:12

Martin Kersten


1 Answers

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.

like image 56
Tavian Barnes Avatar answered Oct 21 '22 17:10

Tavian Barnes