Inject Configuration in Guice AbstractModule in Dropwizard Application

I am working on an application developed using Guice and Dropwizard, where we are creating different bundles like guice bundle, migrations bundle, etc. and adding them to bootstrap in initialize() method.

I am trying to inject Configuration object in MyModule class, but unable to do so.

Following is the code for Application class:

public class MyApplication extends Application<MyConfiguration> {

    public static void main(String args[]) throws Exception {
        new MyApplication().run(args);
    }

    private GuiceBundle<MyConfiguration> guiceBundle = GuiceBundle.<MyConfiguration> newBuilder()
        .addModule(new MyModule()).enableAutoConfig(getClass().getPackage().getName())
        .setConfigClass(MyConfiguration.class).build(Stage.DEVELOPMENT);

    @Override
    public void initialize(Bootstrap<MyConfiguration> bootstrap) {
        bootstrap.addBundle(guiceBundle);
    }

    @Override
    public void run(MyConfiguration configuration, Environment environment) throws Exception {
        ...
    }
}

Below is Module class which extends AbstractModule:

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {

    }
}

With this approach, I am finding it hard to inject Configuration object in Module class, as Configuration object is not available in initialize() method, but is available in run() method.

Is there any alternative way to do this?

Note: I am aware of another way where you can create an object of Module class in run() method for creating an injector (with configuration and environment object passed as parameters in the constructor of MyModule class). But this would require me to register all Managed objects and all resources in run() method. I want to avoid doing that.


Guice modules are classes that store the configuration, and are resolved when an injector is created. You cannot explicitly inject an object in your module.

I don't think I would be able to tell you much more without looking into internal of GuiceBundle .

链接地址: http://www.djcxy.com/p/94652.html

上一篇: 用Guice / GuicePersist注入Hibernate拦截器

下一篇: 在Dropwizard应用程序中的Guice AbstractModule中注入配置