2015-08-28 107 views
0

我在Spring, Java, Ant Web應用程序中工作。我正在使用Spring分析來基於環境加載屬性。下面是示例使用Spring配置文件加載環境屬性

@Profile("dev") 
@Component 
@PropertySource("classpath:dev.properties") 
public class DevPropertiesConfig{ 

} 
@Profile("qa") 
@Component 
@PropertySource("classpath:qa.properties") 
public class TestPropertiesConfig { 

} 

@Profile("live") 
@Component 
@PropertySource("classpath:live.properties") 
public class LivePropertiesConfig{ 

} 

web.xml中,我們可以給輪廓

<context-param> 
     <param-name>spring.profiles.active</param-name> 
     <param-value>dev</param-value> 
    </context-param> 

現在,我的查詢是每一個環境,我需要創建一個單獨的Java類。

問:是否有可能只有一個類如提供配置文件名像@Profile({profile})一些有約束力的參數。

另外,讓我知道是否有其他更好的選擇可用來實現相同。

+0

是的,這是可能的,你做對了。 –

+2

而不是使用基於活動配置文件的'ApplicationContextInitializer'添加指向該配置文件文件的'ResourcePropertySource'。這也是Spring Boot(或多或少)的作用。 –

+0

有關@ M.Deinum答案的詳細示例,請參閱此[SO答案](http://stackoverflow.com/a/8601353/3898076)。 –

回答

0

一次可以有多個配置文件處於活動狀態,因此沒有單個屬性可以獲取活動配置文件。一個通用的解決方案是創建一個基於活動配置文件的ApplicationContextInitializer加載其他配置文件。

public class ProfileConfigurationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { 

    public void initialize(final ConfigurableApplicationContext ctx) { 
     ConfigurableEnvironment env = ctg.getEnvironment(); 
     String[] profiles = env.getActiveProfiles(); 
     if (!ArrayUtils.isEmpty(profiles)) { 
      MutablePropertySources mps = env.getPropertySources(); 
      for (String profile : profiles) { 
       Resource resource = new ClassPathResource(profile+".properties"); 
       if (resource.exists()) { 
        mps.addLast(profile + "-properties", new ResourcePropertySource(resource); 
       } 
      } 
     } 
    } 
} 

像這樣的事情應該做的伎倆(可能包含錯誤,因爲我從我的頭頂鍵入它)。

現在在您的web.xml中包含一個名爲contextInitializerClasses的上下文參數,併爲其指定初始值設定項的名稱。

<context-param> 
    <param-name>contextInitializerClasses</param-name> 
    <param-value>your.package.ProfileConfigurationInitializer</param-value> 
</context-param> 
相關問題