Spring Context提供了国际化支持,可非常方便地实现在不同语言环境下显示不同的文本信息。下面我们来看一下Spring Context的国际化支持。
在Spring Context中,可以使用MessageSource接口访问消息资源。它定义了用于查询消息的操作,同时还提供了一些支持信息格式化的方法。
public interface MessageSource { String getMessage(String code, Object[] args, String defaultMessage, Locale locale);String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException;String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;}
其中,Locale参数用于指定所需的语言环境。我们可以通过ResourceBundleMessageSource实现MessageSource接口,获取指定语言的消息。
public class ResourceBundleMessageSource extends AbstractMessageSource { // ...@Overrideprotected MessageFormat resolveCode(String code, Locale locale) { String key = code + "_" + locale.toString();String msg = messageProperties.getProperty(key);if (msg != null) { return new MessageFormat(msg, locale);} else { return null;}}}
在上述实现中,我们通过Properties对象中指定语言环境的消息来获取指定语言的消息。
在使用Spring Context的国际化支持时,需要创建一个消息源(MessageSource)并且在需要获取多语言的地方注入该消息源即可,举个例子:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" />bean>
其中,basename表示资源文件的前缀,例如上例中消息资源文件为messages_en_US.properties等。
@Autowiredprivate MessageSource messageSource;public void doSth() { String message = messageSource.getMessage("welcome.message", new Object[] { "john"}, Locale.US)// message: "Welcome john!"}
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者