原文: https://howtodoinjava.com/spring-mvc/spring-messagesourceaware-java-bean-example/

如果要将不同语言环境的 i18n 资源包访问到 Java 源代码中,则该 Java 类必须实现MessageSourceAware接口。 在实现MessageSourceAware接口之后,spring 上下文将通过类需要实现的setMessageSource(MessageSource messageSource) setter 方法自动将MessageSource引用注入到类中。

如何在 Spring Bean 中访问MessageSource

如前所述,使您的 bean 类MessageSourceAware成为给定的方式。

  1. package com.howtodoinjava.demo.controller;
  2. import org.springframework.context.MessageSource;
  3. import org.springframework.context.MessageSourceAware;
  4. @Controller
  5. public class EmployeeController implements MessageSourceAware
  6. {
  7. private MessageSource messageSource;
  8. public void setMessageSource(MessageSource messageSource) {
  9. this.messageSource = messageSource;
  10. }
  11. public void readLocaleSpecificMessage()
  12. {
  13. String englishMessage = messageSource.getMessage("first.name", null, Locale.US);
  14. System.out.println("First name label in English : " + englishMessage);
  15. String chineseMessage = messageSource.getMessage("first.name", null, Locale.SIMPLIFIED_CHINESE);
  16. System.out.println("First name label in Chinese : " + chineseMessage);
  17. }
  18. }

现在,Web 应用程序的“资源”文件夹中有两个属性文件。 (文件应在运行时位于类路径中)。

messages_zh_CN.propertiesmessages_zh_CN.properties

  1. #messages_en_US.properties
  2. first.name=FirstName in English
  3. #messages_zh_CN.properties
  4. first.name=FirstName in Chinese

现在测试我们是否能够加载特定于语言环境的属性。

  1. package springmvcexample;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.howtodoinjava.demo.controller.EmployeeController;
  5. public class TestSpringContext
  6. {
  7. @SuppressWarnings("resource")
  8. public static void main(String[] args)
  9. {
  10. ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "/spring-servlet.xml" });
  11. EmployeeController controller = (EmployeeController) context.getBean(EmployeeController.class);
  12. controller.readLocaleSpecificMessage();
  13. }
  14. }
  15. Output:
  16. First name label in English : FirstName in English
  17. First name label in Chinese : FirstName in Chinese

显然,我们能够在 Java Bean 中以特定于语言环境的方式访问资源。

祝您学习愉快!