首页 > 解决方案 > 将 application.yml 值改为小写

问题描述

我目前正在使用 spring.application.name 作为后缀在 elasticsearch 中创建索引,它希望索引为小写格式。

像这样

management:
  metrics:
    export:
      elastic:
        host: ${ES_METRICS_HOST}
        # disabled for local profile
        enabled: true
        # The interval at which metrics are sent to Elastic. The default is 1 minute.
        step: 1m
        # The index to store metrics in, defaults to "metrics"
        index: metrics-${spring.application.name}

我想知道是否有什么方法可以在那个参考上做一个 toLowerCase ?

在文档中找不到

谢谢

标签: spring-bootconfiguration

解决方案


您可以使用自定义EnvironmentPostProcessor解决此问题,我正在测试答案,所以下面是我编写的代码。

  • 为您的应用程序编写一个 CustomEnvironmentPostProcessor,使用@Order(Ordered.LOWEST_PRECEDENCE)由于格式问题而无法添加代码的类注释

下面是类

public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private static final String PROPERTY_SOURCE_NAME = "systemProperties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> map = new HashMap<String, Object>();
        String home = "spring.application.name";
        String key = "management.metrics.export.elastic.index";
        String metricsName = "metrics-" + environment.getProperty(home).toLowerCase();
        map.put(key, metricsName);
        addOrReplace(environment.getPropertySources(), map);
    }

    private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
        MapPropertySource target = null;
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
            if (source instanceof MapPropertySource) {
                target = (MapPropertySource) source;
                for (String key : map.keySet()) {
                    if (!target.containsProperty(key)) {
                        target.getSource().put(key, map.get(key));
                    }
                }
            }
        }
        if (target == null) {
            target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
        }
        if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
            propertySources.addLast(target);
        }
    }

}
  • 编写完 CustomEnvironmentPostProcessor 后,将其注册到应用程序
  • 资源/META-INF 中的cretae spring.factories文件
  • 添加您的CustomEnvironmentPostProcessor的条目(使用您自己的包名称)

下面是入口

org.springframework.boot.env.EnvironmentPostProcessor=com.shailesh.config.CustomEnvironmentPostProcessor

就这样


推荐阅读