Conditionally choosing a Module

757 views
Skip to first unread message

christophe...@gmail.com

unread,
May 22, 2009, 9:09:06 PM5/22/09
to google-guice
Howdy list,

I'm starting my app something like this:

Injector launchInjector = Guice.createInjector(new SettingsModule());
DisplaySettings displaySettings = launchInjector.getInstance
(DisplaySettings.class);
Injector injector = launchInjector.createChildInjector(RenderModule.get
(displaySettings.getRenderer()));

That feels a bit ugly. Is there a prettier way where I can just
conditionally inside a provider (or similar) based on my settings
class chose what modules to create my injectors with?

Thanks for any help!

tzwoenn

unread,
May 24, 2009, 6:21:49 AM5/24/09
to google-guice
With Java 6 you could use the unguicy ServiceLoader (http://
java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) to
configure different Modules on startup time. Just provide a text file
at "META-INF/services/com.google.inject.Module" with the enabled
modules each per line and you can instantiate a Injector like

Guice.createInjector(ServiceLoader.load(Module.class))



On May 23, 3:09 am, "christopher.oestl...@gmail.com"

limpb...@gmail.com

unread,
May 24, 2009, 1:12:05 PM5/24/09
to google-guice
On May 22, 6:09 pm, "christopher.oestl...@gmail.com"
<christopher.oestl...@gmail.com> wrote:
> That feels a bit ugly. Is there a prettier way where I can just
> conditionally inside a provider (or similar) based on my settings
> class chose what modules to create my injectors with?

You should just use plain old Java code. The if statement is the
simplest way to do conditional stuff, and since Guice is configured
via plain code, this is easy:

public static void main(String[] args) {
List<String> argsList = Arrays.asList(args);

List<Module> modules = new ArrayList<Module>();
modules.add(new SettingsModule());
modules.add(new PersistenceModule());

if (argsList.contains("--use_renderer")) {
modules.add(new RenderModule());
}

Injector injector = Guice.createInjector(modules);
injector.getInstance(Service.class).start();
}
Reply all
Reply to author
Forward
0 new messages