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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With