首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将.yml文件中的所有spring引导属性设置为系统属性

将.yml文件中的所有spring引导属性设置为系统属性
EN

Stack Overflow用户
提问于 2017-04-12 04:45:36
回答 1查看 1.9K关注 0票数 1

我正在开发一个spring引导项目,其中传递了许多VM参数,以便应用程序启动,例如cert位置、特定的配置文件类型(不是dev、qa、prod等)。

我正在移动default.yml文件中的所有配置。

问题陈述

default.yml中设置的属性仅可访问spring上下文的环境接口,即org.springframework.core.env.Environment,而属性不会自动/默认设置为

我是通过一个listner ServletContextListenercontextInitialized.方法中设置系统中的属性

但我不想使用environment .getProperty(key)显式地调用所有属性的名称,而是希望将spring上下文中可用的所有属性循环/不循环设置到系统/环境变量中。

期望解

我正在寻找一种方法,在listner方法中,我可以将default.yml文件中定义的所有属性设置为系统属性,而不需要访问它们的名称。

下面是我目前所遵循的将从spring /default.yml提取的活动概要文件设置为system属性的方法。我不想从yml获取活动配置文件或任何属性,但希望.yml中可用的所有属性都自动设置到系统中。

代码语言:javascript
复制
Optional.ofNullable(springEnv.getActiveProfiles())
            .ifPresent(activeProfiles -> Stream.of(activeProfiles).findFirst().ifPresent(activeProfile -> {
                String currentProfile = System.getProperty("spring.profiles.active");
                currentProfile = StringUtils.isBlank(currentProfile) ? activeProfile : currentProfile;
                System.setProperty("spring.profiles.active", currentProfile);
            }));
EN

回答 1

Stack Overflow用户

发布于 2017-04-19 15:22:41

你可能会用到这样的东西:

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Properties;

@Component
public class EnvTest {

    final StandardEnvironment env;

    @Autowired
    public EnvTest(StandardEnvironment env) {
        this.env = env;
    }

    @PostConstruct
    public void setupProperties() {
        for (PropertySource<?> propertySource : env.getPropertySources()) {
            if (propertySource instanceof MapPropertySource) {
                final String propertySourceName = propertySource.getName();
                if (propertySourceName.startsWith("applicationConfig")) {
                    System.out.println("setting sysprops from " + propertySourceName);
                    final Properties sysProperties = System.getProperties();

                    MapPropertySource mapPropertySource = (MapPropertySource) propertySource;
                    for (String key : mapPropertySource.getPropertyNames()) {
                        Object value = mapPropertySource.getProperty(key);
                        System.out.println(key + " -> " + value);
                        sysProperties.put(key, value);
                    }
                }
            }
        }
    }
}

当然,当它为您工作时,请删除stdout消息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43360485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档