Guice和一般应用程序配置

对于用Java编写的监控软件,我考虑使用Google Guice作为DI提供商。 项目需要从外部资源(文件或数据库)加载其配置。 该应用程序旨在以独立模式或servlet容器运行。

目前,配置不包含依赖项注入的绑定或参数,只有一些全局应用程序设置(JDBC连接定义和关联的数据库管理/监视对象)。

我看到两个选择:

  • 使用另一个库,例如Apache Commons Configuration ,它支持文件和JDBC配置源(以及许多其他)

要么

  • 使用Guice -xml-config之类的Guice基于文件的插件来存储应用程序选项(如果有必要,这将允许稍后配置DI部分)。

您是否建议将Guice用于这两项任务,或者将一般应用程序配置与dependency injection分开? 您认为哪些优点和缺点最重要?

在Guice模块中篡改属性文件很简单:

public class MyModule extends AbstractModule { @Override protected void configure() { try { Properties properties = new Properties(); properties.load(new FileReader("my.properties")); Names.bindProperties(binder(), properties); } catch (IOException ex) { //... } } } 

之后,很容易从Properties切换到其他配置源。

[编辑]

顺便说一句,您可以通过@Named("myKey")注释来获取注入的属性。

检查管理者库:

https://github.com/Netflix/governator/wiki/Configuration-Mapping

您将获得@Configuration注释和几个配置提供程序。 在代码中,它有助于查看您使用的配置参数在哪里:

 @Configuration("configs.qty.things") private int numberOfThings = 10; 

此外,您将在启动时获得一个很好的配置报告:

https://github.com/Netflix/governator/wiki/Configuration-Mapping#configuration-documentation

尝试在maven central上提供Guice配置 ,它支持Properties,HOCON和JSON格式。

您可以将文件application.conf中的属性注入到您的服务中:

 @BindConfig(value = "application") public class Service { @InjectConfig private int port; @InjectConfig private String url; @InjectConfig private Optional timeout; @InjectConfig("services") private ServiceConfiguration services; } 

您必须将模块ConfigurationModule安装为

 public class GuiceModule extends AbstractModule { @Override protected void configure() { install(ConfigurationModule.create()); requestInjection(Service.class); } } 

我在自己的项目中遇到了同样的问题。 我们已经选择了Guice作为DI框架并且保持简单,想要将它与配置一起使用。

我们最终使用Apache Commons Configuration从属性文件中读取配置并将它们绑定到Guice注入器,如Guice FAQ中建议的如何注入配置参数? 。

 @Override public void configure() { bindConstant().annotatedWith(ConfigurationAnnotation.class) .to(configuration.getString("configurationValue")); } 

重新加载Commons Configuration支持的配置也非常容易实现到Guice注入。

 @Override public void configure() { bind(String.class).annotatedWith(ConfigurationAnnotation.class) .toProvider(new Provider() { public String get() { return configuration.getString("configurationValue"); } }); }