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

本文介绍了Springboot如何通过i18n实现国际化,包括使用ResourceBundle和MessageSource接口管理不同语言的配置文件,以及在Springboot自动配置中的应用。重点讨论了如何根据客户端请求头中的Accept-Language设置Locale,从而动态加载对应的配置文件并返回给用户。
摘要由CSDN通过智能技术生成

假如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.

*/

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)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 20
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个开发框架,用于简化Java应用程序的配置和部署。它提供了一套用于国际化i18n)的消息资源(MessageSource)的支持。 MessageSource是Spring框架中用来处理国际化消息的接口。它的作用是将应用程序中的文本消息放入一个外部资源文件中,这样可以使得应用程序支持多种语言的消息显示。MessageSource可以加载多个资源文件,每个资源文件对应一种语言。开发人员可以根据需要添加、修改或删除文本消息,而无需修改应用程序的源代码。 在Spring Boot应用中配置MessageSource的步骤如下: 1. 在项目的配置文件(比如application.properties或application.yml)中,设置MessageSource相关的属性,比如资源文件的路径、默认的语言等。 2. 创建一个资源文件,例如messages.properties,将需要国际化的消息以key-value的形式保存在这个文件中。 3. 根据需要,可以创建其他资源文件,如messages_en.properties、messages_zh.properties等,分别对应不同的语言。 4. 在代码中使用MessageSource来获取消息,可以通过@Autowired注解将MessageSource注入到需要使用的类中,然后使用getMessage()方法获取对应的消息内容,根据需要传入参数。 通过MessageSource,开发人员可以实现应用程序的国际化,使得应用程序能够适应不同的地区和语言环境。Spring Boot提供了简单易用的配置和工具,使得国际化变得更加便捷。开发人员只需关注文本消息的准备和配置,而无需关心具体的国际化实现细节。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值