0

如何从 ResourceBundle 切换到 Properties(类)?

我有一个应用程序分为 2 个 Java 项目(核心和网络)。核心模块中的 Java 服务必须从位于 Web 模块中的 .properties 文件中读取值。当我使用 ResourceBundle 时,它​​按预期工作。

我想切换到 Properties 类有几个原因(特别是因为 ResourceBundle 被缓存了,我不想实现 ResourceBundle.Control 没有缓存)。不幸的是,我无法让它工作,特别是因为我找不到要使用的正确相对路径。

我阅读了反编译的 ResourceBundle 类(等),并注意到在某些 ClassLoader 上使用了 getResource()。因此,我没有直接使用 FileInputStream,而是在 ServiceImpl.class 或 ResourceBundle.class 上使用 getResource() 或简单地 getResourceAsStream() 进行测试,但仍然没有成功......

有人知道如何完成这项工作吗?谢谢!

这是我的应用程序核心,服务获取属性值:

app-core
    src/main/java
        com.my.company.impl.ServiceImpl

            public void someRun() {
                String myProperty = null;
                myProperty = getPropertyRB("foo.bar.key"); // I get what I want
                myProperty = getPropertyP("foo.bar.key"); // not here...
            }

            private String getPropertyRB(String key) {
                ResourceBundle bundle = ResourceBundle.getBundle("properties/app-info");
                String property = null;
                try {
                    property = bundle.getString(key);
                } catch (MissingResourceException mre) {
                    // ...
                }
                return property;
            }

            private String getPropertyP(String key) {
                Properties properties = new Properties();

                InputStream inputStream = new FileInputStream("properties/app-info.properties"); // Seems like the path isn't the good one
                properties.load(inputStream);
                // ... didn't include all the try/catch stuff

                return properties.getProperty(key);
            }

这是属性文件所在的 Web 模块:

app-web
    src/main/resources
        /properties
            app-info.properties
4

2 回答 2

3

您应该使用getResource()getResourceAsStream()使用正确的路径和类加载器。

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("properties/app-info.properties");

确保文件名为app-info.properties,而不是(当上下文匹配时)app-info_en.properties找到的文件,而不是.ResourceBundlegetResourceAsStream()

于 2013-01-22T18:21:56.300 回答
3

您不应该尝试从文件系统中读取属性。更改获取属性的方法以从资源流中加载它们。伪代码:

private String getPropertyP(final String key) {
    final Properties properties = new Properties();

    final InputStream inputStream = Thread.currentThread().getContextClassLoader()
       .getResourceAsStream("properties/app-info.properties");
    properties.load(inputStream);

    return properties.getProperty(key);
}
于 2013-01-22T18:22:21.510 回答