最後のチュートリアルでは、//spring/spring-resource-bundle-with-resourcebundlemessagesource-example/[MessageSource via ApplicationContext]というリンクを取得することができます。しかし、BeanがMessageSourceを取得するには、

MessageSourceAware

インタフェースを実装する必要があります。


Springのコンテナ初期化中に、

MessageSourceAware

インタフェースを実装するクラスがあれば、Springは自動的に

setMessageSource(MessageSource messageSource)

setterメソッドを介してクラスにMessageSourceを挿入します。

package com.mkyong.customer.services;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class CustomerService implements MessageSourceAware
{
    private MessageSource messageSource;

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public void printMessage(){
        String name = messageSource.getMessage("customer.name",
                new Object[]{ 28, "/" }, Locale.US);

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

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

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

}

それを実行します

package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
    public static void main( String[]args )
    {
        ApplicationContext context =
            new ClassPathXmlApplicationContext(
                new String[]{"locale.xml","Spring-Customer.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
        cust.printMessage();
    }
}

すべてのプロパティファイルとXMLファイルは、//spring/spring-resource-bundle-with-resourcebundlemessagesource-example/[ResourceBundleMessageSource tutorial]の最後のリンクから再利用されます。

ダウンロードする –

Spring-MessageSource-Example.zip