Configure an object provided by a Guice Module

前端 未结 2 606
一向
一向 2021-01-28 18:00

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

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


        
相关标签:
2条回答
  • 2021-01-28 18:38

    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.
      }  
    }
    
    0 讨论(0)
  • 2021-01-28 18:58

    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(),
                     ...);
    
    0 讨论(0)
提交回复
热议问题