Spring中提供了资源国际化的模板实现,可以通过简单的配置即可实现资源国际化。
下面给个小栗子:
1、配置国际化资源xxx.properties
在resources目录下新建三个文件:
i18n.properties相当于父文件,i18n_xxx.properties相当于子文件,有继承的意思。
文件内容分别为:
welcome=Hello World!
welcome=welcome!
welcome=欢迎!
(注意:idea默认properties文件不是utf-8的所以需要设置下,参考:https://blog.csdn.net/u010285974/article/details/107102644)
2、测试启动类
package com.daquan._202007._01.spring.i18n;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Locale;
public class TestMessageSource {
public static void main(String[] args) {
System.out.println("加载spring容器");
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");
//从容器上下文获取bean(也可以通过实现MessageSourceAware接口来注入该bean)
MessageSource messageResource = (MessageSource)classPathXmlApplicationContext.getBean("messageSource");
String errorCh = messageResource.getMessage("welcome", null,"empty", Locale.SIMPLIFIED_CHINESE);
System.out.println(errorCh);
}
}
3、application.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config />
<!--自动扫描含有@Service将其注入为bean -->
<context:component-scan base-package="com.daquan._202007" />
<!--资源国际化配置-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!--加载resources下i18n开头的资源-->
<property name="basename" value="i18n" />
</bean>
</beans>