Skip to content

Instantly share code, notes, and snippets.

@Yyukan
Last active November 10, 2015 09:49
Show Gist options
  • Save Yyukan/bd11704c9ec5217ae68c to your computer and use it in GitHub Desktop.
Save Yyukan/bd11704c9ec5217ae68c to your computer and use it in GitHub Desktop.
Spring 4 Conditional simple example
package net.oshtykhno.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.stereotype.Component;
/**
* Demo of spring 4 conditional annotation
*
* -Dconfig.condition=local | remote - to define which bean is going to be wired
*/
public class SpringConditionalDemo {
public static void main(String[] args) throws Exception {
System.out.println("Application started...");
final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// setup configuration
applicationContext.scan("net.oshtykhno.spring");
// setup all the dependencies (refresh) and make them run (start)
applicationContext.refresh();
applicationContext.start();
try {
applicationContext.getBean(Config.class).bean.run();
} finally {
applicationContext.close();
}
}
@Component
public static class Config {
@Autowired
MyBean bean;
}
public static class LocalConfigCondition implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return "local".equals(conditionContext.getEnvironment().getProperty("config.condition", "local"));
}
}
public static class RemoteConfigCondition implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return "remote".equals(conditionContext.getEnvironment().getProperty("config.condition"));
}
}
public interface MyBean {
default void run() {
System.out.println("My Bean default is running");
}
}
@Component
@Conditional(LocalConfigCondition.class)
public static final class LocalBean implements MyBean {
public void run() {
System.out.println("Local bean is running");
}
}
@Component
@Conditional(RemoteConfigCondition.class)
public static final class RemoteBean implements MyBean {
public void run() {
System.out.println("Remote bean is running");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment