I have a Module
that provides a JDBI DBI
instance like this:
@Provides
@Singleton
DBI dbi(DataSource dataSource) { return new DBI(dataS
The Guice Injections documentation describes how to invoke an instance method by annotating the method with @Inject.
It doesn't mention that the instance can be a Guice module. As such, you can do this:
class MyConfigurationModule extends AbstractModule {
@Override
protected void configure() {
requestInjection(this);
}
@Inject
void configureDbi(DBI dbi) {
// Do whatever configuration.
}
}
Guice is designed to have many different modules for different purposes. This allows you to swap settings and other injections while leaving others the same.
So you could do something like the following:
Example:
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface ApplicationDBI {}
Example:
@Provides @ApplicationDBI
// Choose the appropriate scope here
protected DBI provideConfiguredDBI(DBI baseDBI) {
// configure the baseDBI here
return baseDBI;
}
Example:
public class DatabaseWrapper {
private final DBI dbi;
@Inject
DatabaseWrapper(@ApplicationDBI DBI dbi) {
this.dbi = dbi;
}
}
Then in your main method:
Injector inj = Guice.createInjector(new DatabaseModule(),
new ApplicationDBIModule(),
...);