Skip to content

Instantly share code, notes, and snippets.

Last active June 12, 2019 00:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crusy/2680fb8e12504f889f6260d003cca90d to your computer and use it in GitHub Desktop.
Save crusy/2680fb8e12504f889f6260d003cca90d to your computer and use it in GitHub Desktop.
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;
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ConditionalOnMissingProperty {
String[] value();
@Order(Ordered.HIGHEST_PRECEDENCE + 40)
class OnMissingPropertyCondition extends SpringBootCondition {
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"));
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)

Copy link

crusy commented Jun 28, 2017

Thanks a lot!

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