JAVA全系列 教程
3762个小节阅读:7088.4k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Spring中国际化是通过MessageSource进行实现的。MessageSource是对java.util.ResourceBundle的上层封装。相对性能要比ResourceBundle有提升。
MessageSource接口提供了三个方法。
xxxxxxxxxx
public interface MessageSource {
/*
code : 内容的key
args : 当内容的value中有占位符时,对占位符的填充
defaultMessage:查找失败的默认消息
locale: 时区,根据时区来选择使用哪个语言集
*/
@Nullable
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;
}
MessageSource接口有三个常用专门做国际化的实现类(ClasspathXmlApplicationContext等也是实现类)。
ApplicationContext接口默认就实现了MessageSource接口。所以ApplicationContext所有实现类都包含国际化功能。
xxxxxxxxxx
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver
准备多个properties文件
可以使用上面的三个属性文件。
配置文件
新建一个配置文件applicationContext-messageSource.xml。
使用MessageSource的实现类ResourceBundleMessageSource。类中包含属性basename,用于设置加载属性文件的基础名称。
xxxxxxxxxx
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="rb"></property>
</bean>
Bean的id必须叫做messageSource,因为在ClassPathXmlApplicationContext的祖先类AbstractApplicationContext中包含全局属性messageSource,如果名称不对应,无法进行注入。
新建测试类
新建com.bjsxt.test.MessageResourceTest。
注入MessageSource后,获取消息。
可以发现,如果Locale对应的国家信息不存在,还是使用服务器的语言编码进行识别。
xxxxxxxxxx
@SpringJUnitConfig
@ContextConfiguration("classpath:applicationContext-messageSource.xml")
public class MessageResourceTest {
@Autowired
MessageSource messageSource;
@Test
void test(){
String remark = messageSource.getMessage("remark", new String[]{"帅", "还是帅"}, Locale.CHINA);
System.out.println(remark);
}
}