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 {
// ...
@Override
protected 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)并且在需要获取多语言的地方注入该消息源即可,举个例子:
- 在configuration.xml文件中创建MessageSource
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
其中,basename表示资源文件的前缀,例如上例中消息资源文件为messages_en_US.properties等。
- 在Java中使用注入的消息源
@Autowired
private MessageSource messageSource;
public void doSth() {
String message = messageSource.getMessage("welcome.message", new Object[] {
"john"}, Locale.US)
// message: "Welcome john!"
}