Spring – BeanでMessageSourceにアクセスする方法(MessageSourceAware)
前回のチュートリアルでは、MessageSource via ApplicationContextを取得できます。 ただし、BeanがMessageSourceを取得するには、MessageSourceAwareインターフェースを実装する必要があります。
例
CustomerServiceクラスは、MessageSourceAwareインターフェイスを実装し、MessageSourceプロパティを設定するためのsetterメソッドを備えています。
Springコンテナの初期化中に、MessageSourceAwareインターフェイスを実装するクラスがある場合、SpringはsetMessageSource(MessageSource messageSource)setterメソッドを介してMessageSourceをクラスに自動的に挿入します。
package com.example.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, "http://www.example.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
String namechinese = messageSource.getMessage("customer.name",
new Object[] { 28, "http://www.example.com" },
Locale.SIMPLIFIED_CHINESE);
System.out.println("Customer name (Chinese) : " + namechinese);
}
}
それを実行します
package com.example.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ファイルは、最後のResourceBundleMessageSource tutorialから再利用されます。