@Conditional根据满足某一个条件创建一个特定的Bean。比如说当一个jar包在一个类路径下时,自动配置一个或多个Bean,或者只有某个Bean被创建时才会创建另一个Bean。Spring Boot中将大量使用到进行一些自动配置。
以下示例根据不同操作系统作为条件,实现condition接口重写matches方法判断条件,若在windows下运行则输出列表命令dir,若在linux下则输出ls。
windows判断条件类
import org.springframework.context.annotation.Condition;import org.springframework.context.annotation.ConditionContext;import org.springframework.core.type.AnnotatedTypeMetadata;/** * @author Kevin * @description * @date 2016/7/1 */public class WindowsCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return conditionContext.getEnvironment().getProperty("os.name").contains("Windows"); }}
linux判断条件
import org.springframework.context.annotation.Condition;import org.springframework.context.annotation.ConditionContext;import org.springframework.core.type.AnnotatedTypeMetadata;/** * @author Kevin * @description * @date 2016/7/1 */public class LinuxCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return conditionContext.getEnvironment().getProperty("os.name").contains("Linux"); }}
命令接口
/** * @author Kevin * @description * @date 2016/7/1 */public interface ListService { public String showListCmd();}
windows条件下创建的Bean类
/** * @author Kevin * @description * @date 2016/7/1 */public class WindowsListService implements ListService { @Override public String showListCmd() { return "dir"; }}
linux条件下创建的Bean类
/** * @author Kevin * @description * @date 2016/7/1 */public class LinuxListService implements ListService { @Override public String showListCmd() { return "ls"; }}
配置类
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Conditional;import org.springframework.context.annotation.Configuration;/** * @author Kevin * @description * @date 2016/7/1 */@Configuration@ComponentScan("ch03.condition")public class ConditionConfig { @Bean // 通过该注解,符合WindowsCondition条件则实例化 @Conditional(WindowsCondition.class) public ListService windowsListService() { return new WindowsListService(); } @Bean @Conditional(LinuxCondition.class) public ListService linuxListService() { return new LinuxListService(); }}
运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * @author Kevin * @description * @date 2016/7/1 */public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class); ListService listService = context.getBean(ListService.class); System.out.println(context.getEnvironment().getProperty("os.name") + "系统下列表命令为:" + listService.showListCmd()); context.close(); }}
结果