tags:

views:

37

answers:

1

I have three Modules in Guice:

  • ReflectionsModule, for providing Metadata (via Reflections)
  • PersistenceModule, for Data Access Objects and Others
  • WebModule, for Web Stuff

Simply put, both PersistenceModule and WebModule will fetch a object which is made from Reflections Module. I can not find a very friendly way to do this in guice.

I think PrivateModules will be a suitable way around, but I am not sure how to implement that. Any ideas?

Thank you.

Some additional details

I am using Reflections. It is basically a wrapper to load persistence metadata from a static resource. So basically supposed a parsed XML file into a JavaBean. Thats the concern of the ReflectionsModule.

From this metadata into the javabean, I need to setup the persistence (its a Google App Engine App, using Objectify) and load additional classes and bind them while reading some annotations within. I do not want to load the resource, so I'd like to refer to the resource loaded from the first example.

For now, the ReflectionsModule also binds the two subsequent modules, which I get (correctly) and apply them to the createChildInjector which came when building with just the first module. As os now, it works. I just would like to know which way would be the best one.

A: 

Simply speaking, PrivateModules expose only bindings that are explicitly exposed using @Exposed annotation of the .expose() method. Therefore, if PersistenceModule and WebModule are both PrivateModules, you can do the following:

public class WebModule extends PrivateModule {
  @Override
  public void configure() {
    install(new ReflectionsModule());
    // do stuff...
    expose(SomeClassFromWebModule.class);
  }
}

public class PersistenceModule extends PrivateModule {
  @Override
  public void configure() {
    install(new ReflectionsModule());
    // do stuff...
    expose(SomeClassFromPersitenceModule.class);
  }
}

In this way, the bindings from ReflectionsModule will not be exposed further than the two PrivateModules and will therefore not run into each other.

It is generally a good practice to only expose classes that can only be provided by one Module.

David Y. Ross