2014-11-25 2 views
3

제 문제는 제가 스프링 프로파일을 사용하는 어플리케이션을 가지고 있다는 것입니다. 서버에서 응용 프로그램을 빌드한다는 것은 프로파일이 "wo-data-init"으로 설정되었음을 의미합니다. 다른 빌드에는 "test"프로필이 있습니다. 그 중 하나가 활성화되면 그들은 콩 방법을 실행 안된다, 그래서 나는이 주석 작동해야하지만 :여러 개의 부정 된 프로필

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

그것이 if(!test OR !wo-data-init)을 실행중인 많은 것 같아 내 경우에는 내가 if(!test AND !wo-data-init)를 실행하는 데 필요 -이다 가능하니?

답변

4

스프링 4는 conditional bean creation에 대한 몇 가지 유용한 기능을 제공합니다. 귀하의 경우에는 OR 연산자를 사용하기 때문에 실제로는 @Profile 주석이 충분하지 않습니다.

사용자가 수행 할 수있는 해결책 중 하나는 맞춤 주석과 맞춤 조건을 만드는 것입니다.

@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의 신속하고 더러운 수정합니다.

이제 방법으로 콩을 주석을 달 수 있습니다 :

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