use*_*533 4 java dependency-injection guice
在我的应用程序中,用户可以在启动程序时在命令行中传递一些参数.在main(String [] args)方法中,我用args4j解析它们.在下一步中,我创建一个Injector(我使用Google Guice),然后获取一个主程序类的实例.命令行参数是我的应用程序的配置设置.我有一个MyAppConfig类,应该存储它们.
如何在注入过程中包含这些命令行参数?我的应用程序的不同类依赖于MyAppConfig,因此必须在几个地方注入它.
我想到的唯一解决方案是创建一个MyAppConfig提供程序,该提供程序具有与命令行参数对应的静态字段,并在使用args4j解析它们之后和使用Injector之前设置它们.然后这样的提供者将使用静态字段创建MyAppConfig.但这看起来很丑陋.还有更优雅的方式吗?
因为您负责创建模块实例,所以可以将它们传递给您想要的任何构造函数参数.您在此处所要做的就是创建一个模块,将您的配置作为构造函数参数,然后在该模块中绑定它.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2273 次 |
| 最近记录: |