2014-11-25 33 views
3

我的問題是,我有應用程序,它使用Spring配置文件。在服務器上構建應用程序意味着該配置文件設置爲「wo-data-init」。對於其他構建有「test」配置文件。當其中任何一個被激活,他們不應該運行Bean的方法,所以我雖然這個註釋應該工作:多個否定配置文件

@Profile({"!test","!wo-data-init"}) 

它似乎更像是它的運行if(!test OR !wo-data-init),並在我的情況,我需要它運行if(!test AND !wo-data-init) - 是它甚至有可能嗎?

回答

4

Spring 4爲conditional bean creation帶來了一些很酷的功能。在你的情況下,確實普通@Profile註釋是不夠的,因爲它使用OR運算符。

您可以做的一個解決方案是爲其創建自定義註釋和自定義條件。例如

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE, ElementType.METHOD}) 
@Documented 
@Conditional(NoProfilesEnabledCondition.class) 
public @interface NoProfilesEnabled { 
    String[] value(); 
} 
public class NoProfilesEnabledCondition implements Condition { 

    @Override 
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { 
     boolean matches = true; 

     if (context.getEnvironment() != null) { 
      MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(NoProfileEnabled.class.getName()); 
      if (attrs != null) { 
       for (Object value : attrs.get("value")) { 
        String[] requiredProfiles = (String[]) value; 

        for (String profile : requiredProfiles) { 
         if (context.getEnvironment().acceptsProfiles(profile)) { 
          matches = false; 
         } 
        } 

       } 
      } 
     } 
     return matches; 
    } 
} 

以上是ProfileCondition快速和骯髒的修改。

現在你可以註釋你的bean的方式:

@Component 
@NoProfilesEnabled({"foo", "bar"}) 
class ProjectRepositoryImpl implements ProjectRepository { ... }