按照一定条件向容器中注入bean的demo演示

68 阅读1分钟

需求:

    根据服务部署的操作系统(windows或者mac)来向IOC容器中注入不同的bean

实战:

1.如何获取操作系统

@Test
public void testCondition() {
  ApplicationContext ac = new AnnotationConfigApplicationContext(PersonConfig7.class);
  Environment environment = ac.getEnvironment();
  String osName = environment.getProperty("os.name");
  System.out.println(osName);
}

image.png

2.利用注解@Conditional来实现功能

1) 相应的bean加入注解

@Configuration
public class PersonConfig7 {

  @Conditional({WindowsCondition.class})
  @Bean
  public Person person01() {
    return new Person("roy", 18);
  }

  @Conditional({LinuxCondition.class})
  @Bean
  public Person person02() {
    return new Person("tom", 20);
  }
}

2)注解的具体实现

/**
 * description:
 * author:dingyawu
 * date:created in 13:46 2020/12/5
 * history:
 */
public class WindowsCondition implements Condition {
    /**
     * ConditionContext:判断条件使用的上下文环境
     * AnnotatedTypeMetadata:注释信息
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //3.获取当前的环境信息
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        return property.contains("Windows");
    }
}


/**
 * description:
 * author:dingyawu
 * date:created in 13:47 2020/12/5
 * history:
 */
public class LinuxCondition implements Condition {
    /**
     * ConditionContext:判断条件使用的上下文环境
     * AnnotatedTypeMetadata:注释信息
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        return property.contains("linux");
    }
}

3)测试代码

@Test
public void testCondition() {
  ApplicationContext ac = new AnnotationConfigApplicationContext(PersonConfig7.class);
  Environment environment = ac.getEnvironment();
  String osName = environment.getProperty("os.name");
  System.out.println(osName);

  String[] names = ac.getBeanNamesForType(Person.class);
  Arrays.stream(names).forEach(System.out::println);

  Map<String, Person> beans = ac.getBeansOfType(Person.class);
  System.out.println(beans);
}