Springboot 集成 i8n,两行代码实现国际化,你不想学吗?(1)

  • @Author Mr.nobody

  • @Date 2021/4/15

  • @Version 1.0

*/

public class LocalTest {

public static void main(String[] args) {

Locale defaultLocale = Locale.getDefault();

Locale chinaLocale = Locale.CHINA;

Locale usLocale = Locale.US;

Locale usLocale1 = new Locale(“en”, “US”);

System.out.println(defaultLocale);

System.out.println(defaultLocale.getLanguage());

System.out.println(defaultLocale.getCountry());

System.out.println(chinaLocale);

System.out.println(usLocale);

System.out.println(usLocale1);

}

}

// 输出结果

zh_CN

zh

CN

zh_CN

en_US

en_US

我们一般会将不同的语言的属性值存放在不同的配置文件中,ResourceBundle类可以根据指定的baseName和Local对象,就可以找到相应的配置文件,从而读取到相应的语言文字,从而构建出ResourceBundle对象,然后我们可以通过ResourceBundle.getString(key)就可以取得key在不同地域的语言文字了。

Properties配置文件命名规则:baseName_local.properties

假如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 集成 i18n

=============================================================================

在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.

*/

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

最近我根据上述的技术体系图搜集了几十套腾讯、头条、阿里、美团等公司21年的面试题,把技术点整理成了视频(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
.cn/images/e5c14a7895254671a72faed303032d36.jpg" alt=“img” style=“zoom: 33%;” />

[外链图片转存中…(img-BhryTvyv-1713401625867)]

最近我根据上述的技术体系图搜集了几十套腾讯、头条、阿里、美团等公司21年的面试题,把技术点整理成了视频(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分

[外链图片转存中…(img-v3vRADFe-1713401625867)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值