對於支持國際化的應用程序,它需要能夠為不同的語言環境解析文本消息。Spring的應用程序上下文能夠通過鍵解析目標語言環境的文本消息。通常,一個語言環境的消息應存儲在一個單獨的屬性文件中。此屬性文件稱為資源包。
MessageSource
是一個接口,它定義了幾種解析消息的方法。該ApplicationContext
接口擴展了此接口,以便所有應用程序上下文都能夠解析文本消息。
應用程序上下文將消息解析委托給具有確切名稱的bean
messageSource
。ResourceBundleMessageSource
是最常見的MessageSource
實現,它解決來自不同語言環境的資源包的消息。
使用ResourceBundleMessageSource解析文本消息
例如,您可以messages_en_US.properties
為美國的英語創建以下資源包。資源包將從類路徑的根目錄加載。
1)創建資源包
messages_en_US.properties
在spring應用程序的類路徑中創建文件名。
messages_en_US.properties
msg.text=Welcome to howtodoinjava.com
2)配置ResourceBundleMessageSource bean定義
現在將ResourceBundleMessageSource
類配置為bean名稱"messageSource"
。此外,您必須指定資源包的基本名稱ResourceBundleMessageSource
。
applicationContext.xml中 <bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>messages</value> </property> </bean>
資源包查找順序
- 對於此
messageSource
定義,如果您查找其首選語言為英語的美國語言環境的文本消息messages_en_US.properties
,則將首先考慮與語言和國家/地區匹配的資源包。 - 如果沒有此類資源包或無法找到該消息,則
messages_en.properties
僅考慮與該語言匹配的消息。 - 如果仍無法找到此資源包,則
messages.properties
最終將選擇所有語言環境的默認值。
演示 - 如何使用MessageSource
1)直接獲取消息
現在檢查是否可以加載消息,運行以下代碼:
TestSpringContext.java public class TestSpringContext { @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ApplicationContext context = newClassPathXmlApplicationContext("applicationContext.xml"); String message = context.getMessage("msg.text", null, Locale.US); System.out.println(message); } }
輸出:
Welcome to howtodoinjava.com
2)在bean中實現MessageSourceAware接口
很好,所以我們能夠解決消息。但是,我們在這里直接訪問,ApplicationContext
所以看起來很容易。如果我們想要訪問某些bean實例中的消息,那么我們需要實現ApplicationContextAware
接口或MessageSourceAware
接口。
像這樣的東西:
EmployeeController.java public class EmployeeController implements MessageSourceAware { private MessageSource messageSource; public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } //Other code }
現在,您可以使用此messageSource
實例來檢索/解析資源文件中定義的文本消息。
轉自:https://blog.csdn.net/u010675669/article/details/86488510