2017-04-12 36 views
0

我正在开发一个Spring引导项目,其中为应用程序启动了许多VM参数以启动ie证书位置,特定配置文件类型(不是开发者,qa,产品等)。
我正在移动default.yml文件中的所有配置。
问题陈述
在default.yml设置的属性是弹簧上下文仅即org.springframework.core.env.Environment的仅环境接口访问和特性不是由默认设置成系统属性自动/ 。
我正在通过列表程序设置系统中的属性ServletContextListener中的方法contextInitialized
但我不想通过使用环境.getProperty(key)明确地调用所有属性的名称,相反,我希望所有可用的属性在spring上下文中都应该循环/无循环地设置到系统/环境变量中。
预计解决方案
我正在寻找一种方法,在listner方法内部,我可以将default.yml文件中定义的所有属性设置为系统属性,而无需通过名称访问属性。将.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); 
      })); 

回答

0

你可能会使用这样的:

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

当然,请取下标准输出的消息时,它的工作对你

+0

嗨Meisch,谢谢您的回答。我结束了做类似的东西:) –