Springでは、 `ResourceBundleMessageSource`を使用して、選択したロケールに基づいたプロパティファイルからのテキストメッセージを解決できます。次の例を参照してください。

1.ディレクトリ構造

この例のディレクトリ構造を見直してください。


この例のディレクトリ構造、title = "spring-resource-folder"、width = 484、height = 341

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}


File:messages

zh

CN.properties

customer.name=\ufeff\u6768\u6728\u91d1, age : {0}, URL : {1}



\ ufeff \ u6768 \ u6728 \ u91d1

‘は中国語のUnicode文字です。

3. Bean設定ファイル

Bean構成ファイルにプロパティー・ファイルを組み込みます。 ”

messages

en

US.properties

“と ”

messages

zh

CN.properties

“はどちらもSpringで1つのファイルを考慮しているだけで、ファイル名を1回だけ含める必要があり、Springは正しいロケールを自動的に見つけます。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>locale\customer\messages</value>
        </property>
    </bean>

</beans>

__P.S両方のファイルが “resources \ locale \ customer \”フォルダにあると仮定します。

4.それを実行する

package com.mkyong.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,"/" }, Locale.US);

        System.out.println("Customer name (English) : " + name);

        String namechinese = context.getMessage("customer.name",
                new Object[]{28, "/" },
                                        Locale.SIMPLIFIED__CHINESE);

        System.out.println("Customer name (Chinese) : " + namechinese);

    }
}


出力


出力、タイトル= "spring-resource-output"、width = 640、height = 264

  • 注意** あなたのリンク://java/how-to-display-chinese-character-in-eclipse-console/[Eclipseは中国語の出力を表示できます]を確認してください。

説明

{空} 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 ‘からメッセージを取得します。

  • その他の情報** この記事を読むと、//spring/spring-how-to-access-messages-in-bean-messagesourceaware/[Bean内部のMessageSource]というリンクにアクセスする方法を知ることができます。

ソースコードをダウンロードする

ダウンロードする –

Spring-MessageSource-Example.zip