Last active
June 12, 2019 00:29
-
-
Save crusy/2680fb8e12504f889f6260d003cca90d to your computer and use it in GitHub Desktop.
This file contains 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 com.acme.condition; | |
import org.springframework.boot.autoconfigure.condition.ConditionMessage; | |
import org.springframework.boot.autoconfigure.condition.ConditionOutcome; | |
import org.springframework.boot.autoconfigure.condition.SpringBootCondition; | |
import org.springframework.context.annotation.ConditionContext; | |
import org.springframework.context.annotation.Conditional; | |
import org.springframework.core.Ordered; | |
import org.springframework.core.annotation.Order; | |
import org.springframework.core.type.AnnotatedTypeMetadata; | |
import org.springframework.util.MultiValueMap; | |
import java.lang.annotation.Documented; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ElementType.TYPE, ElementType.METHOD}) | |
@Documented | |
@Conditional(ConditionalOnMissingProperty.OnMissingPropertyCondition.class) | |
public @interface ConditionalOnMissingProperty { | |
String[] value(); | |
@Order(Ordered.HIGHEST_PRECEDENCE + 40) | |
class OnMissingPropertyCondition extends SpringBootCondition { | |
@Override | |
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { | |
MultiValueMap<String, Object> annotationAttributes | |
= metadata.getAllAnnotationAttributes(ConditionalOnMissingProperty.class.getName()); | |
for (Object values : annotationAttributes.get("value")) { | |
for (String propertyName : (String[]) values) { | |
if (context.getEnvironment().containsProperty(propertyName)) { | |
// return NO match if there is a property of the given name: | |
return ConditionOutcome.noMatch(ConditionMessage.of("Found property " + propertyName)); | |
} | |
} | |
} | |
// return match if no matching property was found: | |
return ConditionOutcome.match(ConditionMessage.of("None of the given properties found")); | |
} | |
} | |
} |
Thanks a lot!
Could you explain please, why did you specify 40 in @Order(Ordered.HIGHEST_PRECEDENCE + 40)
code?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IMO
value
should be mandatory (i.e. without a default value). Adding@ConditionalOnMissingProperty
with no value hasn't lot of sense IMO.The implementation looks ok even though I really thing relying on this is a bad idea (as described in the original issue)