一、消息处理功能
Spring提供MessageSource接口用于提供消息处理功能:
public interface MessageSource { String getMessage(String code, Object[] args, String defaultMessage, Locale locale); String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException; String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException; }
Spring提供了两个默认实现:
StaticMessageSource // 测试用 ResourceBundleMessageSource // 用于生产环境
ApplicationContext
接口扩展了MessageSource
接口,当ApplicationContext
被加载时,它会自动在context中查找已定义为MessageSource
类型的bean。此bean的名称须为messageSource
。如果找到,那么所有对上述方法的调用将被委托给该bean。否则ApplicationContext
会在其父类中查找是否含有同名的bean。如果有,就把它作为MessageSource
。如果它最终没有找到任何的消息源,一个空的StaticMessageSource
将会被实例化,使它能够接受上述方法的调用。
示例如下:
属性文件
# exception.properties message.arg=the {0} {1} is requred. # format.properties message=这是一条测试消息 # format_en_GB.properties message=this is a test
spring 配置(spring-validation.xml)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>format</value> <value>exception</value> </list> </property> <property name="fileEncodings"> <props> <prop key="format">utf-8</prop> </props> </property> </bean> </beans>
测试
public class MessageTest { public static void main(String[] args) { MessageSource ms = new ClassPathXmlApplicationContext("spring-validation.xml"); String msg1 = ms.getMessage("message", null, "yeah", null); String msg2 = ms.getMessage("message.arg", new Object[] { "aa", "bb" }, "yeah", null); // 参数定制 String msg3 = ms.getMessage("message", null, "yeah", Locale.UK); // 支持国际化 System.out.println(msg1); System.out.println(msg2); System.out.println(msg3); } }
运行结果
这是一条测试消息 the aa bb is requred. this is a test
补充:spring提供了MessageSourceAware接口,用于在bean创建时自动注入MessageSource。
参考: