Guice和一般应用程序配置 [英] Guice and general application configuration

查看:175
本文介绍了Guice和一般应用程序配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



我看到两个选项:




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






  • 基于文件的插件(如 guice-xml-config )来存储应用程序选项(这将允许



建议您使用Guice执行这两项任务,或保留常规应用程序配置独立于依赖注入?

解决方案

在Guice模块中直接调用属性文件是很简单的: / p>

  public class MyModule extends AbstractModule {

@Override
protected void configure b $ b try {
属性properties = new Properties();
properties.load(new FileReader(my.properties));
Names.bindProperties(binder(),properties);
} catch(IOException ex){
// ...
}
}
}

以后很容易从属性切换到其他配置源。




$ b

BTW,您可以通过 @Named(myKey)注释注入的属性。


For a monitoring software written in Java I consider using Google Guice as DI provider. The project needs to load its configuration from an external resource (file or database). The application is designed to run in standalone mode or in a servlet container.

At the moment the configuration does not contain bindings or parameters for dependency injection, only some global application settings (JDBC connection definitions and associated database management/monitoring objects).

I see two options:

or

  • to use a file based addon for Guice like guice-xml-config to store the application options (this would allow to configure the DI part later if it becomes necessary).

Would you recommend to use Guice for both tasks, or keep the general application configuration separate from the dependency injection? Which advantages and disadvantages would you consider the most important ones?

解决方案

It's straightforward to slurp a property file in a Guice module:

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) {
        //...
    }
  }
} 

Later it's easy to switch from Properties to other config sources.

[Edit]

BTW, you can get the injected properties by annotating it with @Named("myKey").

这篇关于Guice和一般应用程序配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆