在上一教程中,您可以通过ApplicationContext获取MessageSource 。 但是对于要获取MessageSource的bean,您必须实现MessageSourceAware接口。
例
一个实现MessageSourceAware接口的CustomerService类具有一个setter方法来设置MessageSource属性。
在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, "http://www.mkyong.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
String namechinese = messageSource.getMessage("customer.name",
new Object[] { 28, "http://www.mkyong.com" },
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文件都可以从上一本ResourceBundleMessageSource教程中重用。
标签: 春天
翻译自: https://mkyong.com/spring/spring-how-to-access-messagesource-in-bean-messagesourceaware/