0

ResourceBundleからProperties(クラス)に切り替える方法は?

アプリを2つのJavaプロジェクト(コアとWeb)に分割しています。コアモジュールの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.propertiesResourceBundlegetResourceAsStream()

于 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 に答える