簡體   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