Spring: How to do AND in Profiles?

前端 未结 7 1597
太阳男子
太阳男子 2020-12-25 10:40

Spring Profile annotation allows you to select profiles. However if you read documentation it only allows you to select more than one profile with OR operation. If you speci

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 11:12

    Since Spring 5.1 (incorporated in Spring Boot 2.1) it is possible to use a profile expression inside profile string annotation. So:

    In Spring 5.1 (Spring Boot 2.1) and above it is as easy as:

    @Component
    @Profile("TEST & CONFIG1")
    public class MyComponent {}
    

    Spring 4.x and 5.0.x:

    • Approach 1: answered by @Mithun, it covers perfectly your case of converting OR into AND in your profile annotation whenever you annotate the Spring Bean also with his Condition class implementation. But I want to offer another approach that nobody proposed that has its pro's and con's.

    • Approach 2: Just use @Conditional and create as many Condition implementations as combinations needed. It has the con of having to create as many implementations as combinations but if you don't have many combinations, in my opinion, it is a more concise solution and it offers more flexibility and the chance of implementing more complex logical resolutions.

    The implementation of Approach 2 would be as follows.

    Your Spring Bean:

    @Component
    @Conditional(value = { TestAndConfig1Profiles.class })
    public class MyComponent {}
    

    TestAndConfig1Profiles implementation:

    public class TestAndConfig1Profiles implements Condition {
        @Override
        public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
            return context.getEnvironment().acceptsProfiles("TEST")
                        && context.getEnvironment().acceptsProfiles("CONFIG1");
        }
    }
    

    With this approach you could easily cover more complex logical situations like for example:

    (TEST & CONFIG1) | (TEST & CONFIG3)

    Just wanted to give an updated answer to your question and complement other answers.

提交回复
热议问题