Last active
August 29, 2015 14:01
-
-
Save maciejwalkowiak/18db36aa646edf431579 to your computer and use it in GitHub Desktop.
ConditionalOnPropertiesPresent - Spring Boot custom conditional example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo; | |
import org.springframework.context.annotation.Conditional; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
@Conditional(OnPropertiesPresentCondition.class) | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ ElementType.TYPE, ElementType.METHOD }) | |
public @interface ConditionalOnPropertiesPresent { | |
String[] value() default {}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.boot.autoconfigure.condition.ConditionOutcome; | |
import org.springframework.boot.autoconfigure.condition.SpringBootCondition; | |
import org.springframework.context.annotation.ConditionContext; | |
import org.springframework.core.type.AnnotatedTypeMetadata; | |
public class OnPropertiesPresentCondition extends SpringBootCondition { | |
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { | |
String[] properties = (String[]) metadata.getAnnotationAttributes( | |
ConditionalOnPropertiesPresent.class.getName()).get("value"); | |
ConditionOutcome conditionOutcome = ConditionOutcome.match(); | |
for (String property : properties) { | |
if (!context.getEnvironment().containsProperty(property)) { | |
conditionOutcome = ConditionOutcome.noMatch("Required property " + property + " not found"); | |
break; | |
} | |
} | |
return conditionOutcome; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment