2

I use an external service to provide properties, but want to make those properties available as @Named(..) vars. Trying to do this in a configure method fails with npe:

Names.bindProperties(binder(), myPropRetriever.getProperties());

is failing because the myPropRetriever isn't appearing until guice has done it's work. I can see why this makes sense - anyone know of any funky hacks that might work around though? Would be handy in this instance..

Mark D
  • 5,368
  • 3
  • 25
  • 32
  • 1
    Related: http://stackoverflow.com/questions/13242957/how-do-you-make-dynamic-bindings-in-guice-that-require-an-injected-instance – durron597 May 17 '15 at 18:11
  • hey thanks! this got me in the right direction! Will post the fix below in case others hit the same circle of love – Mark D May 18 '15 at 20:41
  • 1
    There wasn't enough information about your system for me to answer your question myself, i.e. what code do you have that is "supposed" to create the `myPropRetriever` instance, but I thought that might help. – durron597 May 18 '15 at 20:42

1 Answers1

1

Thanks to durron597 for the pointer to the related question which gave me enough to figure out. The answer is to use a child injector to take action on the previous injectors output. Example below:

Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));

Injector is now your injector for the remainder of the app.

And then in MyModule you can take action on the created objects:

public class MyModule extends AbstractModule {
private final Properties properties;

public MyModule(Properties properties){
    this.properties=properties;
}

@Override
protected void configure() {
    // export all the properties as bindings
    Names.bindProperties(binder(), properties);

    // move on to bindings
    // bind(..);
}

}

In case it helps anyone else..!

Mark D
  • 5,368
  • 3
  • 25
  • 32