自定义@Conditional注解

通过自定义注解@ConditionOnSystemProperties实现条件装配。

  1. 自定义注解@ConditionOnSystemProperties,需要在@Conditional注解中传入实现Condition接口的类;

    1. @Target({ ElementType.TYPE, ElementType.METHOD })
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Conditional(OnSystemPropertiesCondition.class)
    5. public @interface ConditionOnSystemProperties {
    6. String key();
    7. String value();
    8. }
  2. 创建OnSystemPropertiesCondition类,并实现Condition接口;通过判断@ConditionOnSystemProperties注解中的key与value是否与环境变量所匹配,来控制装配;

    1. public class OnSystemPropertiesCondition implements Condition {
    2. @Override
    3. public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    4. Map<String, Object> attributes = metadata.getAnnotationAttributes("com.xxx.ConditionOnSystemProperties");
    5. String key = (String) attributes.get("key");
    6. String value = (String) attributes.get("value");
    7. String property = System.getenv(key);
    8. return value.equals(property);
    9. }
    10. }
  3. 创建ConditionalBootstrap启动类,并定义一个名称为“sayHello”的Bean;装配条件是环境变量中存在名为“name”的变量,且“name”的值为“lily”;

    1. public class ConditionalBootstrap {
    2. @Bean
    3. @ConditionOnSystemProperties(key = "name", value = "lily")
    4. public String sayHello() {
    5. return "hello";
    6. }
    7. public static void main(String[] args) {
    8. ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalBootstrap.class)
    9. .web(WebApplicationType.NONE)
    10. .run(args);
    11. String sayHello = context.getBean("sayHello", String.class);
    12. System.out.println(sayHello);
    13. context.close();
    14. }
    15. }
  4. 由于环境变量中不存在名为“name”的变量,所以获取Bean失败。运行结果如下图: image.png

  5. 向环境变量中添加名为“name”值为“lily”的变量,IntelliJ IDEA中可以使用如下方式添加环境变量; image.png
  6. 运行结果如下图: image.png