【问题标题】:Set all spring boot properties inside .yml file into system properties将 .yml 文件中的所有 Spring Boot 属性设置为系统属性
【发布时间】:2017-09-07 16:48:01
【问题描述】:

我正在开发一个 Spring Boot 项目,其中传递了许多 VM 参数以启动应用程序,即证书位置、特定配置文件类型(不是 dev、qa、prod 等)。
我正在将所有配置移到 default.yml 文件中。
问题陈述
default.yml 中设置的属性只能由 spring 上下文的环境接口访问,即 org。仅 springframework.core.env.Environment 并且 属性不会自动/默认设置到系统属性中
我正在通过侦听器 ServletContextListener 在系统中设置属性在 contextInitialized 方法中。
但我不想使用 environment .getProperty(key) 按名称显式调用所有属性,而是希望所有属性在 spring 上下文中可用的应该循环/不循环设置到系统/环境变量中。
预期的解决方案
我正在寻找一种方法,使用该方法在 listner 方法中,我可以将 default.yml 文件中定义的所有属性设置为系统属性,而无需通过其名称访问属性。

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

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);
            }));

【问题讨论】:

    标签: java spring-boot keystore jvm-arguments vmargs


    【解决方案1】:

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

    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);
                        }
                    }
                }
            }
        }
    }
    

    当然,当它对你有用时,请删除标准输出消息

    【讨论】:

    • 您好 Meisch,感谢您的回答。我最终做了类似的事情:)
    最近更新 更多