繁体   English   中英

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

[英]How to switch from ResourceBundle to Properties (class)?

如何从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

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

InputStream inputStream = getClass()。getClassLoader()。getResourceAsStream(“ properties / app-info.properties”);

确保该文件名为app-info.properties ,而不是诸如app-info_en.properties类的app-info_en.properties ,该名称将由ResourceBundle (在上下文匹配时)找到,而不是由getResourceAsStream()

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

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM