2014-09-01 103 views
2

當我們在春天爲任何組件定義配置文件時,我們將其聲明爲 @Profile(value="Prod")。但我想從屬性文件中給出該值。 這可能嗎?如果是,如何?創建ApplicationContext的時候在屬性佔位符值中使用@Profile註釋

+0

你是什麼意思給屬性文件的值?你的意思是隻有在配置文件處於活動狀態時才需要包含屬性文件? – geoand 2014-09-01 09:01:44

+0

No ..我想要的配置文件名稱來自屬性文件 – MasterCode 2014-09-01 09:10:50

+0

您的'@Profile(「$ {propertyName}」)'爲''propertyName'來自'application.properties'嗎? – geoand 2014-09-01 09:11:41

回答

2

通過彈簧的源代碼去,我已經到了這樣的結論:你問是不可能的。爲了清楚說明,Spring無法評估在@Profile之內。

特別看看ProfileCondition,它檢查配置文件是否處於活動狀態。

class ProfileCondition implements Condition { 

    @Override 
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { 
     if (context.getEnvironment() != null) { 
      MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName()); 
      if (attrs != null) { 
       for (Object value : attrs.get("value")) { 
        if (context.getEnvironment().acceptsProfiles(((String[]) value))) { 
         return true; 
        } 
       } 
       return false; 
      } 
     } 
     return true; 
    } 

} 

肉是context.getEnvironment().acceptsProfiles(((String[]) value))

現在,如果你檢查的AbstractEnvironment源,其中acceptsProfiles所在,你會發現,在控制到達

protected boolean isProfileActive(String profile) { 
    validateProfile(profile); 
    return doGetActiveProfiles().contains(profile) || 
      (doGetActiveProfiles().isEmpty() && doGetDefaultProfiles().contains(profile)); 
} 

不嘗試計算表達式,但需要字符串逐字(也無處前注意isProfileActive是正在評估的字符串表達式)

你可以找到我上面提到的代碼herehere


另一個說明,我不知道爲什麼你需要有一個動態配置文件名稱。

1

另一種方法是:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigClass.class); 
String profile = aplicationContext.getEnvironemnt().getRequiredProperty("profile"); 
applicationContext.getEnvironment().setActiveProfiles(profile); 
+0

這是設置活動配置文件,但我想要他什麼時候我創建一個組件併爲其設置值,該值應該來自屬性文件 – MasterCode 2014-09-01 09:34:03

+0

另外,當使用Spring Boot時,您可能不想採用這種方法 – geoand 2014-09-01 09:35:06

+0

是嗎?如果我使用除'application.properties'以外的任何其他屬性文件並使用@PropertySource annotaton – MasterCode 2014-09-01 09:42:40

3

您似乎試圖濫用@Profile註釋。使用配置文件來啓用功能。並不是說Bean在特定的環境中是活躍的。

一種實現更接近我認爲你正在尋找的東西的方法是獲得特定於你的環境的屬性文件,它定義了應該在其中激活的配置文件。通過這種方式,你可以用ARG如啓動您的應用程序:

--spring.profiles.active=prd 

那麼春天開機時會試圖加載application-prd.properties,在那裏你可以激活特定的環境配置文件:

spring.profiles.active=sqlserver,activedirectory,exchangeemail 

這樣,你的豆只有在他們提供的功能是必需的時纔會被激活。