Skip to content

Instantly share code, notes, and snippets.

@maciejwalkowiak
Last active August 29, 2015 14:01
Show Gist options
  • Save maciejwalkowiak/18db36aa646edf431579 to your computer and use it in GitHub Desktop.
Save maciejwalkowiak/18db36aa646edf431579 to your computer and use it in GitHub Desktop.
ConditionalOnPropertiesPresent - Spring Boot custom conditional example
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 {};
}
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