假如baseName为i18n,则相应的配置文件应该命名为如下:
-
中文的配置文件:i18n_zh_CN.properties
-
英文的配置文件:i18n_en_US.properties
然后在两个配置文件中,存放着键值对,对应不同的语言文字
在i18n_zh_CN.properties文件中
userName=陈皮
在i18n_en_US.properties文件中
userName=Peel
我们通过如下方式,就可以获取相应语言环境下的信息了,如下:
Locale chinaLocale = Locale.CHINA;
ResourceBundle resourceBundle = ResourceBundle.getBundle(“i18n”, chinaLocale);
String userName = resourceBundle.getString(“userName”);
System.out.println(userName);
Locale usLocale = Locale.US;
resourceBundle = ResourceBundle.getBundle(“i18n”, usLocale);
userName = resourceBundle.getString(“userName”);
System.out.println(userName);
// 输出结果
陈皮
Peel
对于不同地域语言环境的用户,我们是如何处理国际化呢?其实原理很简单,假设客户端发送一个请求到服务端,在请求头中设置了键值对,“Accept-Language”:“zh-CN”,根据这个信息,可以构建出一个代表这个区域的本地化对象Locale,根据配置文件的baseName和Locale对象就可以知道读取哪个配置文件的属性,将要显示的文字格式化处理,最终返回给客户端进行显示。
=============================================================================
在Springboot中,我们会使用到一个MessageSource接口,用于访问国际化信息,此接口定义了几个重载的方法。code即国际化资源的属性名(键);args即传递给格式化字符串中占位符的运行时参数值;local即本地化对象;resolvable封装了国际化资源属性名,参数,默认信息等。
-
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale)
-
String getMessage(String code, @Nullable Object[] args, Locale locale)
-
String getMessage(MessageSourceResolvable resolvable, Locale locale)
Springboot提供了国际化信息自动配置类MessageSourceAutoConfiguration,它可以生成MessageSource接口的实现类ResourceBundleMessageSource,注入到Spring容器中。MessageSource配置生效依靠ResourceBundleCondition条件,从环境变量中读取spring.messages.basename的值(默认值messages),这个值就是MessageSource对应的资源文件名称,资源文件扩展名是.properties,然后通过PathMatchingResourcePatternResolver从classpath*:
目录下读取对应的资源文件,如果能正常读取到资源文件,则加载配置类。源码如下:
package org.springframework.boot.autoconfigure.context;
@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = {};
// 我们可以在application.properties文件中修改spring.messages前缀的默认值,比如修改basename的值
@Bean
@ConfigurationProperties(prefix = “spring.messages”)
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
// 生成ResourceBundleMessageSource实例,注入容器中
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
messageSource.setBasenames(StringUtils
.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
protected static class ResourceBundleCondition extends SpringBootCondition {
private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<>();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty(“spring.messages.basename”, “messages”);
ConditionOutcome outcome = cache.get(basename);
if (outcome == null) {
outcome = getMatchOutcomeForBasename(context, basename);
cache.put(basename, outcome);
}
return outcome;
}
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition(“ResourceBundle”);
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
return ConditionOutcome.match(message.found(“bundle”).items(resource));
}
}
}
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
// 读取classpath*:路径下的配置文件
private Resource[] getResources(ClassLoader classLoader, String name) {
String target = name.replace(‘.’, ‘/’);
try {
return new PathMatchingResourcePatternResolver(classLoader)
.getResources(“classpath*:” + target + “.properties”);
}
catch (Exception ex) {
return NO_RESOURCES;
}
}
}
}
以下这个类是Spring国际化处理的属性配置类,我们可以在application.properties文件中自定义修改这些默认值,例如:spring.messages.basename=i18n
。
package org.springframework.boot.autoconfigure.context;
/**
-
Configuration properties for Message Source.
-
@author Stephane Nicoll
-
@author Kedar Joshi
-
@since 2.0.0
*/
public class MessageSourceProperties {
/**
-
Comma-separated list of basenames (essentially a fully-qualified classpath
-
location), each following the ResourceBundle convention with relaxed support for
-
slash based locations. If it doesn’t contain a package qualifier (such as
-
“org.mypackage”), it will be resolved from the classpath root.
*/
private String basename = “messages”;
/**
- Message bundles encoding.
*/
private Charset encoding = StandardCharsets.UTF_8;
/**
-
Loaded resource bundle files cache duration. When not set, bundles are cached
-
forever. If a duration suffix is not specified, seconds will be used.
*/
最后
我还为大家准备了一套体系化的架构师学习资料包以及BAT面试资料,供大家参考及学习
已经将知识体系整理好(源码,笔记,PPT,学习视频)
ation. When not set, bundles are cached
- forever. If a duration suffix is not specified, seconds will be used.
*/
最后
我还为大家准备了一套体系化的架构师学习资料包以及BAT面试资料,供大家参考及学习
已经将知识体系整理好(源码,笔记,PPT,学习视频)
[外链图片转存中…(img-O0I74DUe-1714460077104)]
[外链图片转存中…(img-kuUPf37e-1714460077105)]
[外链图片转存中…(img-VnsOvULq-1714460077106)]