Spring学习笔记(五)

1、ApplicationContext国际化支持(继承MessageSource类):

package org.springframework.context;

import java.util.Locale;

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;
} 

2、新建bean4.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:oscache="http://www.springmodules.org/schema/oscache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/springmodules-oscache.xsd">

	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames" >
			<list>
				<value>message</value>
			</list>
		</property>	
	</bean>
	
</beans>

3、测试类test2:

package com.test;

import java.util.Date;
import java.util.Locale;

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

public class Test2 {

	public static void main(String[] args) {
		
		ApplicationContext apc = new ClassPathXmlApplicationContext("Bean3.xml");
//		String hello = apc.getMessage("hello", new String[]{"傻逼"}, Locale.US);
		String hello = apc.getMessage("hello", new String[]{"傻逼"}, Locale.getDefault());
		System.out.println(hello);
//		String now = apc.getMessage("now", new Object[]{new Date()}, Locale.US);
		String now = apc.getMessage("now", new Object[]{new Date()}, Locale.getDefault());
		System.out.println(now);
	}
}

4、美式资源文件(message_en_US.properties):

hello=welcome,{0}
now=now is {0}

5、中式资源文件(message_zh_CN.properties):

hello=\u4F60\u597D{0}
now=\u73B0\u5728\u65F6\u95F4\u662F\: {0}

6、中式资源文件可通过native2ascii命令进行转换

native2ascii   message.properties   message_zh_CN.properties

7、打印信息:

中文环境下:
你好傻逼
现在时间是: 12-11-5 下午4:19

英文环境下:
welcome,傻逼
now is 11/5/12 4:24 PM

猜你喜欢

转载自luan.iteye.com/blog/1717164