ResourceBundleMessageSourceを使用したSpringリソースバンドルの例
Springでは、ResourceBundleMessageSource
を使用して、選択したロケールに基づいて、プロパティファイルからテキストメッセージを解決できます。 次の例を参照してください。
1. ディレクトリ構造
この例のディレクトリ構造を確認します。
2. プロパティファイル
2つのプロパティファイルを作成します。1つは英語の文字(messages_en_US.properties
)用で、もう1つは漢字用(messages_zh_CN.properties
)です。 プロジェクトクラスパスに配置します(上の図を参照)。
ファイル:messages_en_US.properties
customer.name=Yong Mook Kim, age : {0}, URL : {1}
ファイル:messages_zh_CN.properties
customer.name=\ufeff\u6768\u6728\u91d1, age : {0}, URL : {1}
‘杨木金‘は中国語のUnicode文字です。
Note
漢字を正しく表示するには、「http://www.example.com/java/java-convert-chinese-character-to-unicode-with-native2ascii/」を使用する必要があります。 [native2ascii]」ツールを使用して、漢字をUnicode文字に変換します。
3. Bean構成ファイル
プロパティファイルをBean構成ファイルに含めます。 「messages_en_US.properties」と「messages_zh_CN.properties」はどちらもSpringの1つのファイルと見なされ、ファイル名を1回含めるだけで、Springは正しいロケールを自動的に検出します。
locale\customer\messages
P.S Assume both files are located at “resources\locale\customer\u201d folder.
4. それを実行します
package com.example.common; import java.util.Locale; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("locale.xml"); String name = context.getMessage("customer.name", new Object[] { 28,"http://www.example.com" }, Locale.US); System.out.println("Customer name (English) : " + name); String namechinese = context.getMessage("customer.name", new Object[] {28, "http://www.example.com" }, Locale.SIMPLIFIED_CHINESE); System.out.println("Customer name (Chinese) : " + namechinese); } }
出力
Note
Eclipse is able to display Chinese outputを確認してください。
説明
1. context.getMessage()
では、2番目の引数はメッセージパラメータです。オブジェクト配列として渡す必要があります。 利用可能なパラメーター値がない場合は、nullを渡すことができます。
context.getMessage("customer.name",null, Locale.US);
2. Locale.USは ‘messages_en_US.properties‘からメッセージを取得し、Locale.SIMPLIFIED_CHINESEは ‘messages_zh_CN.properties‘からメッセージを取得します。
More …
この記事を読んで、MessageSource inside a beanにアクセスする方法を確認してください。