繁体   English   中英

Spring 引导:尝试使用 EnvironmentPostProcessor 覆盖 application.properties

[英]Spring Boot: Attempting to override application.properties using EnvironmentPostProcessor

所以我试图使用存储在 Cosul 中的键/值来覆盖 application.properties 中的值。 我尝试了两件事。

1) 使用 Spring 云领事配置。 https://cloud.spring.io/spring-cloud-consul/reference/html/#spring-cloud-consul-config

如果我的 application.properties 中没有定义相同的键,这将起作用。 如果它是在 application.properties 中定义的,则属性文件中的值将用于所有 @Value 注释解析。 这与我想要的相反。

2)由于上面没有工作,我继续创建一个自定义的EnvironmentPostProcessor。 我首先尝试构建一个 MapPropertySource 并使用 environment.getPropertySources().addAfter(..)。 这与上面的结果相同。 然后我尝试遍历所有属性源,找到名称包含“applicationConfig:[classpath:/application”的属性源,并设置属性值(如果存在)或放置一个新的属性值。 此外,我将 MapPropertySource 添加到“applicationConfig: [classpath:/application” 属性源所在的 EnumerableCompositePropertySource 中。

无论采用哪种方法,结果总是相同的。 如果 key 存在于 application.properties 中,则使用该值。

是什么赋予了? 我实际上是在覆盖属性源中的值,并且在 PostProcessor 完成它的工作之前,我可以在调试器中看到这些值。 application.properties 值如何仍然到达@Value 注释?

这是我当前的后处理器。

@Order(Ordered.LOWEST_PRECEDENCE)
public class ConsulPropertyPostProcessor implements EnvironmentPostProcessor {


    private static final String PROPERTY_SOURCE_NAME = "applicationConfigurationProperties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        PropertySource<?> system = environment.getPropertySources().get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

        ConsulKVService consulKVService = new ConsulKVServiceImpl().instantiateConsulKVServiceImpl((String)system.getProperty("CONSUL_HOST"), (String)system.getProperty("CONSUL_TOKEN"));
        Map<String, Object> map = consulKVService.getConsulKeysAndValuesByPrefix((String)system.getProperty("CONSUL_PREFIX"));


        addOrReplace(environment.getPropertySources(), map);
    }

    private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
        MapPropertySource target = new MapPropertySource("applicationConfig: [consulKVs]", map);
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource<?> applicationConfigurationPropertySources = propertySources.get(PROPERTY_SOURCE_NAME);

            for(EnumerableCompositePropertySource applicationPropertySource : (ArrayList<EnumerableCompositePropertySource>)applicationConfigurationPropertySources.getSource()){
                if(applicationPropertySource.getName() != null
                        && applicationPropertySource.getName().contains("applicationConfig: [profile=")) {

                    for(PropertySource singleApplicationPropertySource : applicationPropertySource.getSource()){
                        if(singleApplicationPropertySource.getName().contains("applicationConfig: [classpath:/application")){

                            for (String key : map.keySet()) {
                                if(map.get(key) != null) {
                                    if (singleApplicationPropertySource.containsProperty(key)) {
                                        ((Properties) singleApplicationPropertySource.getSource())
                                                .setProperty(key, (String) map.get(key));
                                    } else {
                                        ((Properties) singleApplicationPropertySource.getSource()).put(key, (String) map.get(key));
                                    }
                                }
                            }
                            break;
                        }
                    }

                    applicationPropertySource.add(target);

                    break;


                }
            }

        }

    }
}

提前谢谢大家。

编辑:尝试覆盖 ApplicationListener class 的 onApplicationEvent 方法,结果与上述相同。 这是那个代码。

@Log4j
public class ConsulProperties implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    static ConfigurableEnvironment configurableEnvironment;
    private static final String PROPERTY_SOURCE_NAME = "applicationConfigurationProperties";

    public static ConfigurableEnvironment getConfigurableEnvironment() {
        return configurableEnvironment;
    }

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        log.info("Received ApplicationEnvironmentPreparedEvent...");
        ConfigurableEnvironment environment = event.getEnvironment();
        configurableEnvironment = environment;
        Properties props = new Properties();

        ConsulKVService consulKVService = new ConsulKVServiceImpl()
                .instantiateConsulKVServiceImpl((String) configurableEnvironment.getProperty("CONSUL_HOST"),
                        (String) configurableEnvironment.getProperty("CONSUL_TOKEN"));
        Map<String, Object> map = consulKVService.getConsulKeysAndValuesByPrefix((String) configurableEnvironment.getProperty("CONSUL_PREFIX"));
        while(map.values().remove(null));
        addOrReplace(environment.getPropertySources(), map);
    }


    private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
        MapPropertySource target = new MapPropertySource("applicationConfig: [consulKVs]", map);
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource<?> applicationConfigurationPropertySources = propertySources.get(PROPERTY_SOURCE_NAME);

            for(EnumerableCompositePropertySource applicationPropertySource : (ArrayList<EnumerableCompositePropertySource>)applicationConfigurationPropertySources.getSource()){
                if(applicationPropertySource.getName() != null
                        && applicationPropertySource.getName().contains("applicationConfig: [profile=")) {

                    for(PropertySource singleApplicationPropertySource : applicationPropertySource.getSource()){
                        if(singleApplicationPropertySource.getName().contains("applicationConfig: [classpath:/application")){

                            for (String key : map.keySet()) {
                                if (singleApplicationPropertySource.containsProperty(key)) {
                                    ((Properties) singleApplicationPropertySource.getSource())
                                            .setProperty(key, (String) map.get(key));
                                } else {
                                    ((Properties) singleApplicationPropertySource.getSource()).put(key,
                                            map.get(key));
                                }
                            }


                            applicationPropertySource.add(target);

                            Properties properties = new Properties();
                            properties.putAll(map);
                            propertySources.addLast(new PropertiesPropertySource("consulKVs", properties));

                            break;
                        }
                    }


                    break;


                }
            }
        }
    }
}

看起来您正在尝试更改 spring 不适合的约定。 您提供的代码不容易维护,需要深入了解 Spring 内部结构。 坦率地说,如果不调试如何实现您想要的,我无法判断,但是我有另一种方法:

您可以通过以下方式使用 spring 配置文件:

假设您在application.properties中有一个属性db.name=abc ,在 consul 中有一个属性 db.name db.name=xyz ,我假设您的目标是让 spring 解析db.name=xyz

在这种情况下,将db.name=abc移动到application-local.properties并使用--spring.profiles.active=local启动应用程序,如果你想从本地文件中获得属性,如果你想没有这个配置文件go 与领事。

您甚至可以在EnvironmentPostProcessor中动态添加一个活动配置文件(无论如何您已经到了那里),但这是 EnvironmentPostProcessor 中的一行代码。

您的代码存在问题,您使用以下代码添加新的属性源。 请注意,当您调用“addLast”时,通过此方法添加的属性源优先级最低,并且永远不会更新已经可用的属性。

propertySources.addLast(new PropertiesPropertySource("consulKVs", properties));

您可以使用“addFirst”代替上面的添加属性源,该属性源应具有最高优先级,如下面的代码所示。 还有一些其他方法,例如“addAfter”和“addBefore”,您可以探索它们以在确切位置添加属性源。 无论如何,“addFirst”将优先于所有其他方式,所以我认为您可以使用“addFirst”来更新属性源。

propertySources.addFirst(new PropertiesPropertySource("consulKVs", properties));

我已经使用 ApplicationEnvironmentPreparedEvent 测试了这个场景,它工作正常。 希望它能解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM