SpringMvc之@Conditional注解

doublespring注解

@Conditational 是根据满足某一个特定条件创建一个特定Bean的条件注解。

通过 application.properties 配置不同的值,结合 @Conditional、@Configuration、@Bean、Condition接口加载不同的bean。
1、controller

@RestController public class MyTest { @Autowired private Hero hero; @GetMapping("/api/first") public String first() { hero.say(); return "233"; } }

2、定义接口和实现类

// 接口 public interface Hero { public void say(); } // 实现类1 public class ZhanSan implements Hero { @Override public void say() { System.out.println("我是张三"); } } // 实现类2 public class ZhaoLiu implements Hero { @Override public void say() { System.out.println("我是赵六"); } }

3、实现 condition 接口

// 张三 public class ZhanSanCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // 通过 getEnvironment 可以获取到系统配置 Environment environment = context.getEnvironment(); String type = environment.getProperty("com.isyxf"); return type.equals("zhanSan"); } } // 赵六 public class ZhaoLiuCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String type = environment.getProperty("com.isyxf"); return type.equals("zhaoLiu"); } }

4、通过 @Conditional 判断加载bean条件

@Configuration public class HeroBean { @Bean @Conditional(ZhanSanCondition.class) public Hero zhanSan() { return new ZhanSan(); } @Bean @Conditional(ZhaoLiuCondition.class) public Hero zhaoLiu() { return new ZhaoLiu(); } }

5、application.properties 文件

// zhaoLiu(加载 ZhaoLiu Bean),zhanSan(加载 ZhanSan Bean) com.isyxf=zhaoLiu