从多个类访问Java配置

时间:2018-09-08 00:57:14

标签: java oop configuration apache-commons-config

我正在探索在Java中进行简单的,基于普通文件的配置的方法。我研究了Java的内置Properties和Apache Common Configuration库。对于后者,摘要代码如下:

Configurations configs = new Configurations();
Configuration config = null;
try
{
    config = configs.properties(new File("config.properties"));
}
catch (ConfigurationException cex)
{
}

long loadQPS = config.getInt("loadQPS");

我遇到的问题是,我发现自己将其插入每个类,由于至少两个原因,它不是最优的:1)我为每个类都读取一次文件,而我应该只读取一次。 2)代码重复。

一个显而易见的解决方案是创建一个Singleton配置类,然后从其他所有类访问该类。但是可以肯定的是,几乎在每个用例中这都是一个理想的功能,因此它不应该包含在配置库中吗(我遗漏了什么)?我还考虑过使用Spring配置,该配置可以为我创建Singleton配置类,但是仅基于文件的配置是否有太多开销? (据我了解,Spring的优势在于DI。)

什么是好的解决方案或最佳实践(如果有)?

编辑:答案中建议的一种简单的静态解决方案:

public class ConfigClass {

    static Configuration config;

    static {
        Configurations configs = new Configurations();

        Logger sysLogger = LoggerFactory.getLogger("sysLogger");
        try
        {
            config = configs.properties(new File("config.properties"));
        }
        catch (ConfigurationException cex)
        {
            sysLogger.error("Config file read error");
        }
    }
}

通过ConfigClass.config访问软件包。

1 个答案:

答案 0 :(得分:2)

因此,您有两种选择。一种简单的方法是静态存储和访问Configuration对象。

当我想要没有Spring的依赖注入时,我喜欢的另一种方法是以DI友好的方式构造程序。您可以通过将main()函数转换为程序的“配置”并最终启动它来模拟DI容器。

考虑一个典型的多层Web应用程序:DI友好的main()方法可能类似于:

public class AddressBookApp {
  public static void main(String[] args) {
    Configuration conf = new Configuration(args[0]);

    // Creates our Repository, this might do some internal JDBC initialization
    AddressBookRepository repo = new AddressBookRepository(conf);

    // Pass the Repository to our Service object so that it can persist data
    AddressBookService service = new AddressBookService(repo);

    // Pass the Service to the web controller so it can invoke business logic
    AddressBookController controller = new AddressBookController(conf, service);

    // Now launch it! 
    new WebApp(new Controller[] { controller }).start();
  }
}

此main()充当“连接”应用程序的中心位置,因此可以轻松地将Configuration对象传递给需要它的每个组件。