【问题标题】:Apache Commons Configuration2 - multiple same name config files from classpathApache Commons Configuration2 - 来自类路径的多个同名配置文件
【发布时间】:2017-01-18 13:20:12
【问题描述】:

我想要做的是与这个问题完全相同的事情:Using Class.getResourcesAsStream to get Apache Commons Configuration,但使用的是 Apache Commons Configuration 2。

到目前为止,我已经尝试在类路径中使用 test.properties 制作第一个 maven 项目:

test1=value1

然后,我在类路径中使用另一个 test.properties 制作了另一个 maven 项目:

test2=value2

在第二个项目中,我对第一个项目添加了依赖项,并创建了一个主要项目:

public static void main(String[] args) throws Exception {

    Configurations configurations = new Configurations();
    PropertiesConfiguration configuration = configurations.properties("test.properties");
    System.out.println(configuration.getString("test1"));

}

当我运行主程序时,我想得到value1,但我得到了null。显然,我创建 PropertiesConfiguration 的方式不会读取第一个模块中存在的 test.properties 文件。

有什么想法或建议来实现这一点吗?

【问题讨论】:

    标签: java configuration apache-commons-config


    【解决方案1】:

    我设法通过使用getClassLoader().getResources("...") 获取 URL,然后遍历这些 URL 以加载属性文件并将它们放在 CompositeConfiguration 中来做到这一点。

    不过,我希望 Apache Commons Configuration2 直接处理这个用例。

    也许有更漂亮的方式存在?

    public static void main(String[] args) throws Exception {
    
        Configurations configurations = new Configurations();
        CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
    
        Enumeration<URL> urls = ConfigurationTest2.class.getClassLoader().getResources("test.properties");
        while(urls.hasMoreElements()) {
            PropertiesConfiguration propertiesConfiguration = configurations.properties(urls.nextElement());
            compositeConfiguration.addConfiguration(propertiesConfiguration);
        }
        System.out.println(compositeConfiguration.getString("test1"));
    
    }
    

    【讨论】:

    • 多个test.properties文件是在不同的包里吗?
    • 不,这就是重点。对于这个 POC,我将两个 test.properties 都放在 src/main/resources
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多