Search code examples
javaspringannotations

How to specify multiple conditions using @Conditional annotation


I am doing a Spring project for the first time and am stuck with a problem.

I have a java class:

@Component
@Conditional(AppA.class)
public class AppDeploy {...}

Now I need to modify this like:

@Component
@Conditional(AppA.class or AppB.class)
public class AppDeploy {...}

Can someone help me with how to do this? Thanks in anticipation.


Solution

  • It was very simple, Should have taken a little time before posting the question. Here is how I did it.

    Created a new Class:

    public class AppAOrB implements Condition {
        public AppAOrB() {
            super();
        }
    
        @Override
        public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
            Environment env = conditionContext.getEnvironment();
            return env.containsProperty("APP_A")||env.containsProperty("APP_B");
        }
    }
    

    Then used it like:

    @Component
    @Conditional(AppAOrB.class)
    public class AppDeploy {...}