Configure an object provided by a Guice Module

醉酒当歌 提交于 2019-12-20 04:24:40

问题


I have a Module that provides a JDBI DBI instance like this:

@Provides
@Singleton
DBI dbi(DataSource dataSource) { return new DBI(dataSource); }

In another module I want to call some initialization methods on that DBI instance (configuring support for particular data types). It's not appropriate logic to put in the JDBI module itself as it's application specific not general to any application using JDBI. Is there a hook for me to do that kind of "extra" configuration?

I tried using the bindListener method but it seems like that's not invoked for objects provided in this way.


回答1:


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.
  }  
}



回答2:


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:

  • Create an annotation for your application to use with your DBI dependency injection:

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 {}
  • Create a second module for DBI specific to your application.

Example:

@Provides @ApplicationDBI
// Choose the appropriate scope here
protected DBI provideConfiguredDBI(DBI baseDBI) {
    // configure the baseDBI here
    return baseDBI;
}
  • Annotate the application injection with your new annotation

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(),
                 ...);


来源:https://stackoverflow.com/questions/24310018/configure-an-object-provided-by-a-guice-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!