Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Conditional Annotation Operator

I need to put a condition on two configuration classes for spring security. When the condition is true, use configuration A, and when the condition is false, use configuration B.

I currently use two condition classes. They produce opposite results.

Is it possible for me to use some operator in the conditional annotation? Something like this?

@Conditional( value = !MyCondition.class )
like image 712
Alic Avatar asked Nov 17 '16 19:11

Alic


People also ask

What is @conditional annotation in spring?

Introduction. In this tutorial, we'll take a look at the @Conditional annotation. It's used to indicate whether a given component is eligible for registration based on a defined condition.

What is ConditionalOnExpression?

The @ConditionalOnExpression annotation allows configurations based on the result of a SpEL expression . Spring will use the marked definition when the SpEL expression evaluated to true @Controller @ConditionalOnExpression("${controller.enabled}) public class WebController { // ... }

What is the @configuration in spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

What is @ConditionalOnProperty in spring?

The Spring framework provides the @ConditionalOnProperty annotation precisely for this purpose. In short, the @ConditionalOnProperty enables bean registration only if an environment property is present and has a specific value. By default, the specified property must be defined and not equal to false.


1 Answers

@Conditional annotation receives a class name that implements the Condition interface and creates the bean if that condition is matched.

If the condition you're trying to implement is simply the negation of another existing condition then you can extend from the existing condition and override the matchesmethod as the negation of invoking the parent class matches method.

like image 192
cjungel Avatar answered Oct 11 '22 12:10

cjungel