【问题标题】:Access application.properties from messages.properties从 messages.properties 访问 application.properties
【发布时间】:2016-10-18 12:47:14
【问题描述】:

我需要从messages.properties中的application.properties访问属性:

application.properties

max-size=3

messages.properties

alert.error=You can only save {max-size} items.

不工作:

{max-size}, #{max-size}, ${max-size}

我知道 this 线程,但我需要它在任何 Java 文件之外。

更新: maven 方法适用于 application.properties 文件,但不适用于 application.properties 和 messages.properties。不应该有订单吗?如果文件 A 有密钥 a 但首先解析文件 B 时,a 在 B 中不可用,是吗?

来自我的 pom.xml 的片段:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>

"#{alert.error(${@environment.getProperty('max-size')})}"

【问题讨论】:

  • 在构建时从 application.properties 获取这些属性有什么价值? Spring 的最佳实践是使用 @value 为属性注入值。
  • @IssamELATIF 的语法是什么? alert.error=你只能保存???max-size???项目。
  • 语法应该是 alert.error=您只能保存 {} 项,然后使用 MessageSource 获取消息。我删除了我的答案,因为它与@g00glen00b 的建议相同。

标签: java spring spring-boot internationalization


【解决方案1】:

要么使用构建工具 (Maven/Gradle/...) 替换它,要么在消息中使用参数,如下所示:

alert.error=You can only save {0} items.

现在您可以自动连接您的MessageSource 并检索您的maxSize

@Autowired
private MessageSource messageSource;
@Value("${max-size}")
private int maxSize;

然后你可以这样使用它:

messageSource.getMessage("alert.error", new Object[]{maxSize}, locale);

此解决方案还允许您将消息用于其他尺寸,而不仅仅是 3。

如果你想在你的视图中使用它(例如使用 Thymeleaf),你可以这样做:

<p th:text="#{alert.error(${@environment.getProperty('max-size')})}"></p>

【讨论】:

  • 我更喜欢这种实现,因为它更符合弹簧要求
  • 消息对话框最终会在服务器响应失败后以角度指令触发,因此 Thymeleaf 和 Java 是没有选择的。
  • 如果在服务器响应失败后该消息应该可见,那么您必须将该消息从您的服务器 (= Java) 发送到您的前端 (= AngularJS)。一旦响应失败,您可以在 Java 代码中使用 messageSource.getMessage()
【解决方案2】:

如果您在 maven 中构建,您可以在构建时过滤 message.properties。

https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

【讨论】:

    【解决方案3】:

    你可以通过 maven 调用资源插件目标 https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

    messages.properties 放在 src/main/resources 中

    <build>
            <filters>
                <filter>src/main/resources/application.properties</filter>
            </filters>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    

    调用mvn resources:resources

    【讨论】:

      猜你喜欢
      • 2014-05-04
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2021-12-08
      • 2011-01-04
      相关资源
      最近更新 更多