Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include command line parameters in the injection process?

In my application a user can pass some parameters in a command line when starting the program. In the main(String[] args) method I parse them with args4j. In the next step I create an Injector (I use Google Guice) and then get an instance of a main program class. The command line parameters are my application's configuration settings. I have a MyAppConfig class where they should be stored.

How I can include these command line parameter in the injection process? Different classes of my application depend on MyAppConfig so it has to be injected in a few places.

The only solution that comes up to my mind is to create a MyAppConfig provider which has static fields corresponding to the command line parameters and set them once I parse them using args4j and before I use Injector. Then such provider would be creating a MyAppConfig using the static fields. But this looks rather ugly. Is there any more elegant way to do it?

like image 730
user2850533 Avatar asked Dec 25 '22 19:12

user2850533


1 Answers

Because you're responsible for creating your module instances, you can pass them whatever constructor arguments you want. All you have to do here is to create a module that takes your configuration as a constructor argument, and then bind that within that module.

class YourMainModule() {
  public static void main(String[] args) {
    MyAppConfig config = createAppConfig(); // define this yourself

    Injector injector = Guice.createInjector(
        new ConfigModule(config),
        new YourOtherModule(),
        new YetAnotherModule());

    injector.getInstance(YourApplication.class).run();
  }
}

class ConfigModule extends AbstractModule {
  private final MyAppConfig config;

  ConfigModule(MyAppConfig config) {
    this.config = config;
  }

  @Override public void configure() {
    // Because you're binding to a single instance, you always get the
    // exact same one back from Guice. This makes it implicitly a singleton.
    bind(MyAppConfig.class).toInstance(config);
  }
}
like image 155
Jeff Bowman Avatar answered Dec 28 '22 11:12

Jeff Bowman