在我的应用程序中,用户在启动程序时可以在命令行中传递一些参数。在main(String[] args)方法中,我使用args4j解析它们。在接下来的步骤中,我创建一个Injector (我使用Google ),然后获取一个主程序类的实例。命令行参数是我的应用程序的配置设置。我有一个应该存储它们的MyAppConfig类。
如何在注入过程中包含这些命令行参数?我的应用程序的不同类依赖于MyAppConfig,因此必须在几个地方注入它。
我想到的唯一解决方案是创建一个具有与命令行参数相对应的静态字段的MyAppConfig提供程序,并在使用args4j和Injector之前对它们进行解析。然后,这样的提供者将使用静态字段创建一个MyAppConfig。但这看起来很难看。还有什么更优雅的方法吗?
发布于 2013-10-06 00:20:31
因为您负责创建模块实例,所以可以传递任何您想要的构造函数参数。这里所要做的就是创建一个以配置为构造函数参数的模块,然后将其绑定到该模块中。
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);
}
}https://stackoverflow.com/questions/19203128
复制相似问题