Spring注解04 @Conditional 按条件注入bean

@Conditional({Condition}) : 按照一定的条件进行判断,满足条件给容器中注册bean

  • 配置类
@Configuration
@ComponentScan(value = "com.tommy", useDefaultFilters = false)
public class MainConfigConditional {

    @Bean(value = "linux")
    @Conditional(LinuxConditional.class)
    public Person person01() {
        System.out.println("linux person 初始化....");
        return new Person("jm", 36, "服务器端开发");
    }

    @Bean(value = "window")
    @Conditional(WindowsCoditional.class)
    public Person person02() {
        System.out.println("window person 初始化....");
        return new Person("jb", 16, "前端开发");
    }
}
  • 条件类 LinuxConditional.java
public class LinuxConditional implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        final Environment environment = context.getEnvironment();
        final String property = environment.getProperty("os.name");
        //WindowsCoditional.java中,只需要判断 Windows
        if (property.contains("linux")) {
            return true;
        }
        return false;
    }
}

测试类

 public class IOCTestConditional {
    @Test
    public void testImport() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigConditional.class);
        System.out.println("IOC容器创建完成...");
        final Person bean = applicationContext.getBean(Person.class);
        System.out.println("bean "+bean);
    }
}

运行结果

window person 初始化....
IOC容器创建完成...
bean Person(name=jb, age=16, nickName=前端开发)

Process finished with exit code 0

如果需要修改当前的操作系统:
VM options
-Dos.name=linux

你可能感兴趣的:(Spring注解04 @Conditional 按条件注入bean)