Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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"));
}
}
}
@snicoll

This comment has been minimized.

Copy link

snicoll commented Jun 27, 2017

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)

@crusy

This comment has been minimized.

Copy link
Owner Author

crusy commented Jun 28, 2017

Thanks a lot!

@Scopers

This comment has been minimized.

Copy link

Scopers commented Feb 15, 2019

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
You can’t perform that action at this time.