0

Say I have a Module structure like this:

Root
|--SubModuleA
  |-BaseModule
|--SubModuleB
  |-BaseModule

SubModuleA and SubModuleBare intended to be used seperatly but also in one application like in this example. And both install the same BaseModule.

Guice allows to declare the same bindings several times if they are exactly the same. In another SO-thread this is referred to as "binding de-duplication".

This works fine for simple bindings, but using a FactoryModuleBuilder in the BaseModule results in a CreationException complaining that

"A binding to ... was already configured at [...]FactoryModuleBuilder$1.configure()"

I checked, that the binding really is declared only in one Module. And removing the binding results into an error stating that the binding is missing. So I assume that it is not possible to declare the same binding more than one time using a FactoryModuleBuilder. Is that true? Is there a way around this?

treeno
  • 2,510
  • 1
  • 20
  • 36

1 Answers1

0

Yes, you can get around this by instead doing

Root
|--BaseModule
|--SubModuleA
|--SubModuleB

All modules together define the registered bindings of the injector. Only in special cases should it be actually necessary to install another module inside of a module, apart from readability.

kutschkem
  • 7,826
  • 3
  • 21
  • 56
  • 1
    Using this design would mean, that a user of i.e. SubModuleA had to know that SubModuleA has a dependency to BaseModule. This is knowledge that should be hidden inside the module (encapsulation, information hiding). In very small applications you might be able to use this Kind of design, but in bigger applications this would weaken maintainability. – treeno Feb 28 '18 at 12:07
  • 2
    @treeno True... It seems that Guice does deduplicate Modules, not just bindings, base on the equals(..) method of the Module. https://github.com/google/guice/issues/659#issue-37299969 Can you try implementing equals() on the Module and see if that works? – kutschkem Feb 28 '18 at 13:17