user1731553
user1731553

Reputation: 1937

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.

Upvotes: 3

Views: 5849

Answers (3)

snieguu
snieguu

Reputation: 2283

I have a slightly different approach. From your code, I can conclude(Maybe I am wrong) that You have already implemented conditions AppA.class and AppB.class and You wonder how to implement the AppAOrB.class condition in an elegant way. When You take into account that AppA.class and AppB.class are just regular java classes, then implementation is obvious:

public class AppAOrB implements Condition {

    @Override
    public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
        return new AppA().matches(context, metadata) || new AppB().matches(context, metadata);
    }
}

The pros of this approach is that it follows the DRY rule.

Upvotes: 1

user1731553
user1731553

Reputation: 1937

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 {...}

Upvotes: 1

jMounir
jMounir

Reputation: 495

You can create your own conditional annotation which enables you to provide parameters and then you can apply the tests conditions depending on the provided parameter value:

see this post for more details: http://www.javacodegeeks.com/2013/10/spring-4-conditional.html

Upvotes: 1

Related Questions