【问题标题】:What is best way to externalize error messages(resource bundles) out of src code in spring and springboot?在 spring 和 springboot 中从 src 代码中外部化错误消息(资源包)的最佳方法是什么?
【发布时间】:2019-05-30 06:33:02
【问题描述】:

我正在寻找将验证错误消息从 spring 和 spring boot 应用程序中的 src 代码外部化的最佳方法,以避免在每次错误消息更改时构建/部署。有没有这样的方法可以实现?

【问题讨论】:

  • 您可以将它们移动到 taml 配置文件中,并在配置类中进行映射。使用配置类中的字段来填充错误消息。如果您需要更改任何内容,只需更改 yaml 配置中的实际消息,重新启动您的服务。

标签: java resourcebundle externalizable


【解决方案1】:

您可以在属性文件中维护所有验证错误或成功消息。如果要外化,可以将属性文件放在spring boot jar文件之外。无需将配置放入 jar 中。我在下面提供了代码sn-p来实现它。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

    @Configuration
    @PropertySources({
      @PropertySource("file:config/other-config.properties"),
      @PropertySource("file:config/app-config.properties")
    })
    public class ExternalConfig {

      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }

在上面的代码中,在@PropertySource("file:config/app-config.properties") 行中,config 是文件夹或目录的名称,其中包含许多属性文件,例如“app-config.properties”。为了更好的理解,我在下面提供了图片,外部配置文件和spring boot jar最终会是这样的。

【讨论】:

    【解决方案2】:

    默认资源包框架假定您的资源包是资源文件夹中的属性文件。因此,它们作为构建过程的一部分被打包在您的 jar 文件中。

    但是你可以实现自己的ResourceBundle加载:

    https://docs.oracle.com/javase/tutorial/i18n/resbundle/control.html

    然后您可以选择使用其他机制,包括使用数据库而不是属性文件(使用 TTL 来缓存特定时间段内的消息)。这样,您甚至不必在消息更改时重新启动应用程序。

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 2011-03-28
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多