您的位置:首页 > 编程语言 > Java开发

Spring-国际化信息03-容器级的国际化信息资源

2017-08-12 13:07 525 查看
导读

概述

实例

注意事项

导读

Spring-国际化信息01-基础知识

Spring-国际化信息02-MessageSource接口

Spring-国际化信息03-容器级的国际化信息资源

概述

我们查看ApplicationContext中的源码可以看到

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver


ApplicationContext 实现了 MessageSource 接口。

在一般情况下,国际化信息资源应该是容器级。我们一般不会将MessageSource作为一个Bean注入到其他的Bean中,相反MessageSource作为容器的基础设施向容器中所有的Bean开放。

国际化信息一般在系统输出信息时使用,如Spring MVC的页面标签,控制器Controller等,不同的模块都可能通过这些组件访问国际化信息,因此Spring就将国际化消息作为容器的公共基础设施对所有组件开放。

Spring根据反射机制从BeanDefinitionRegistry中找出名称为“messageSource”且类型为org.springframework.context.MessageSource的Bean,将这个Bean定义的信息资源加载为容器级的国际化信息资源.

实例

代码已托管到Github—> https://github.com/yangshangwei/SpringMaster



资源文件

greeting.common=How are you {0}?,today is {1}
greeting.morning=Good Morning {0}! now is {1,time,short}
greeting.afternoon=Good Afternoon {0}! now is {1,date,long}


配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
<!--①注册资源Bean,其Bean名称只能为messageSource -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" ref="resourceList"/>
</bean>

<util:list id="resourceList">
<value>i18n/fmt_resource</value>
</util:list>

</beans>


测试类

package com.xgj.ioc.i18n.container;

import java.util.GregorianCalendar;
import java.util.Locale;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ContainerI18NTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:com/xgj/ioc/i18n/container/beans.xml");
// 动态参数
Object[] params = { "XiaoGongJiang", new GregorianCalendar().getTime() };
// 直接通过容器访问国际化信息
String msg1 = ctx.getMessage("greeting.common", params, Locale.US);
String msg2 = ctx.getMessage("greeting.morning", params, Locale.CHINA);
System.out.println(msg1);
System.out.println(msg2);
}
}


运行结果:



注意事项

MessageSource Bean名字必须命名为“messageSource”,以上代码将抛出NoSuchMessageException异常

假设我们将id=”messageSource” 改为 id=”messageSource1”

再此运行

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: