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>