Spring MessageSourceAware Java Bean 示例

Spring MessageSourceAware Java Bean 示例

原文: 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成为给定的方式。

package com.howtodoinjava.demo.controller;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

@Controller
public class EmployeeController implements MessageSourceAware
{
	private MessageSource messageSource;

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void readLocaleSpecificMessage()
	{
	String englishMessage = messageSource.getMessage("first.name", null, Locale.US);

    	System.out.println("First name label in English : " + englishMessage);

    	String chineseMessage = messageSource.getMessage("first.name", null, Locale.SIMPLIFIED_CHINESE);

    	System.out.println("First name label in Chinese : " + chineseMessage);
	}
}

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

messages_zh_CN.propertiesmessages_zh_CN.properties

#messages_en_US.properties
first.name=FirstName in English

#messages_zh_CN.properties
first.name=FirstName in Chinese

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

package springmvcexample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.howtodoinjava.demo.controller.EmployeeController;

public class TestSpringContext 
{
	@SuppressWarnings("resource")
	public static void main(String[] args) 
	{
		ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "/spring-servlet.xml" });

		EmployeeController controller = (EmployeeController) context.getBean(EmployeeController.class);

		controller.readLocaleSpecificMessage();
	}
}

Output:

First name label in English : FirstName in English
First name label in Chinese : FirstName in Chinese

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

祝您学习愉快!