java - 自定义 Spring Boot 启动器 : how do you contribute i18n messages to the MessageSource?

标签 java spring internationalization spring-boot

我正在编写一个自定义的 Spring Boot starter,其他开发人员将把它放入他们的应用程序中,这个 starter 包含开箱即用的 Controller 和 UI 屏幕。

这些 UI 屏幕是国际化的,i18n 键/值位于包文件中:com/foo/wherever/i18n.properties

我想确保当我的启动器在启动时加载时,这些 i18n.properties 在应用程序的 MessageSource 中自动可用,以便我的 UI 页面工作(通过普通的 Spring Controller + ViewResolver +查看实现)应用开发者无需自己指定此文件

换句话说,他们应该能够将我的启动器添加到他们的运行时类路径中,并且一切都“正常工作”,而无需配置任何东西。

现在,我发现应用程序开发人员可以创建自己的src/main/resources/messages.properties 文件中手动配置附加消息文件>应用程序属性:

spring.messages.basename = messages, com.foo.wherever.i18n

这会起作用。

但是,这需要满足以下两个条件:

  1. 他们必须手动配置 spring.messages.basename 属性——它不是自动的。和
  2. 他们的应用程序类路径中必须有自己的messages.properties 文件。如果 messages.properties 文件不存在,spring.messages.basename 甚至不会工作。即使他们不关心 i18n,这仍然是必需的——不可取。

我想我可以将我的 i18n.properties 文件移动到 starter.jar 中的 classpath:/messages.properties 文件,但这似乎不是一个好的解决方案:如果应用程序开发人员有自己的 messages.properties 文件,只有其中一个会被读取,导致消息值丢失。

好像是Spring Boot MessageSourceAutoConfiguration应该有一个 CompositeMessageSource 的概念,它迭代一个或多个 MessageSource 实例,这些实例在 Spring ApplicationContext 和 < em>that 由 DispatcherServlet 使用。这将允许任何启动器仅通过在其自动配置中声明 MessageSource

来为可用消息做出贡献

可以按照我的要求做吗?对于应用开发者来说,最“放手”的解决方案是什么?

最佳答案

我是这样设置的。我目前仅支持 en_US,但它已设置为使用国际化 (i18n) 处理任意数量的语言。

在这里查看代码

在此处查看代码要点:Code on github gist

添加消息源和默认语言环境 Bean

将这些 bean 添加到您的 Application.java 以设置您的默认语言环境并配置您的消息 Prop 的位置

Message source and default locale


创建消息服务

服务将从 session 中获取默认语言环境,然后从您的 Prop 中获取消息文本

Setup Message svc


在Controller中使用消息服务

注入(inject)消息svc然后传入id从props文件中获取值

Use svc in controller


在语言环境中添加 message.properties 文件

转到/资源:

  • 创建语言环境文件夹
  • 创建一个名为 messages_en_US.properties 的文件

message props


阅读更多

您可以在此处查看有关此主题的更完整的文章: Spring Boot Internationalization i18n using Message Properties


看代码

在此处查看代码要点: Code on github gist

关于java - 自定义 Spring Boot 启动器 : how do you contribute i18n messages to the MessageSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28750292/

相关文章:

java - 领域模型和实体模型是否相同

java - 是否可以在 Spring Boot 应用程序中使用具有冗余功能的 HashiCorp Vault?

c++ - 有没有一种方法可以使用带有 C++ 的 MFC 来更改线程的语言环境

Django i18n : Specifying context. (msgctxt)

scala - 如何从 Scala Play 中提供大部分静态页面!应用程序像不同语言的 "About"页面?

java - 如何从 JFrame 中删除 JPanel?

java - 如何在已调用的方法中引用对象?

c# - 将 C# 转换为 java

java - 如何在 Spring AMQP 中解析 JSON 对象?

java - 带有日期参数的 TimeZone 和 MessageFormat