2017-04-12 35 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,謝謝您的回答。我結束了做類似的東西:) –