spring根据环境变量判断是否加载bean

2020-12-14  本文已影响0人  iamdev

假如我们有个需求,我们有多个实现了相同接口的bean,需要在不同环境变量下只加载某个bean,那么应该怎么做呢?

举个例子,假如我们有两套环境,一套生产环境,一套测试环境,使用环境变量RUNTIME来区别,其中测试环境的RUNTIME=TEST,生产环境是RUNTIME=PRODUCT,在不同环境变量下,需要的mysql的地址也是不同的,测试环境可能是localhost,生产环境可能是云环境,也可能是其它的地址。

这里只是举个例子,来说明如何不同环境变量下激活不同的bean,当然可能有其它更好的办法,例如spring的Profile。
接下来我们用代码来实际解决这个问题。

创建一个接口,接口的含义是获取mysql的host

public interface MysqlHost {
    String getMysqlHost();
}

然后是这个接口的两个实现类

@Component
public class ProductMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "mysql-product-server";
    }
}

@Component
public class TestMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "localhost";
    }
}

创建一个使用类

@Component
public class UseMysql {
    @Autowired
    private MysqlHost mysqlHost;
    public UseMysql(){
        System.out.println(mysqlHost.getMysqlHost());
    }
}

这样其实会有一个问题,那就是我们有两个MysqlHost的实现bean类,无法使用AutoWired

我们需要在特定环境下加载特定的bean,比如test环境就加载TestMysqlHost的实现bean,生产环境加载ProductMysqlHost实现类

翻了下spring这方面的文档,发现有一个@ConditionalOnProperty可以实现在特定的propertity下加载bean,但是该注解无法做到在环境变量下加载bean,所以不符合需求。
但是spring提供了一种可以灵活定制condition的方式,就是@Conditional 注解和Condition 接口结合起来定制更加复杂灵活的bean加载机制。

接下来看看具体代码怎么实现
首先实现两个condition类

public class ProductCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext,
        AnnotatedTypeMetadata annotatedTypeMetadata) {
        return "PRODUCT".equals(System.getenv("RUNTIME"));
    }
}

public class TestCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext,
        AnnotatedTypeMetadata annotatedTypeMetadata) {
        return !"PRODUCT".equals(System.getenv("RUNTIME"));
    }
}

然后只需要在bean的实现类里使用@Conditional(<>.class)方式即可

@Component
@Conditional(ProductCondition.class)
public class ProductMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "mysql-product-server";
    }
}
@Component
@Conditional(TestCondition.class)
public class TestMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "localhost";
    }
}

这样我们使用@AutoWired注入MysqlHost的时候,spring会根据对应配置的条件来决定加载哪一个bean

这样确实可以满足我们的需求,但是还是不够灵活,因为以后如果我们新增了环境变量,或者需要其它环境变量,那么就需要额外新增很多condition来判断,这样肯定不够灵活。

下面使用一种更加灵活的方式,那就是使用自定义注解的方式

声明一个EnvCondition的注解类,该注解类里面包含了envKey,envValue,和判断条件相等或者不相等

@Retention(RetentionPolicy.RUNTIME)
public @interface EnvCondition {

  String envKey();

  String envValue();

  Type type();

  enum Type {
    Equals, NotEquals
  }
}

EnvConditions注解类可以把多个EnvCondition条件进行组合

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(EnvConditionsHandler.class)
public @interface EnvConditions {
  EnvCondition[] value();
}

最后我们实现condition接口,具体的逻辑就是读取注解里面的变量,然后组合判断是否符合当前的环境变量的要求。

public class EnvConditionsHandler implements Condition {


  @Override
  public boolean matches(ConditionContext conditionContext,
      AnnotatedTypeMetadata annotatedTypeMetadata) {
    Map<String, Object> envConditionMap = annotatedTypeMetadata
        .getAnnotationAttributes(EnvConditions.class.getName());
    if (Objects.nonNull(envConditionMap)) {
      AnnotationAttributes[] value = (AnnotationAttributes[]) envConditionMap.get("value");
      boolean result = true;
      for (AnnotationAttributes attributes : value) {
        String envKey = attributes.getString("envKey");
        Enum<Type> type = attributes.getEnum("type");
        String envValue = attributes.getString("envValue");
        if (Type.Equals.name().equals(type.name())) {
          result = result && envValue.equals(System.getenv(envKey));
        } else {
          result = result && !envValue.equals(System.getenv(envKey));
        }
      }
      return result;
    } else {
      return false;
    }
  }
}

具体应用如下:

@Component
@EnvConditions({@EnvCondition(envKey = "RUNTIME", type = Type.Equals, envValue = "PRODUCT")})
public class ProductMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "mysql-product-server";
    }
}
@Component
@EnvConditions({@EnvCondition(envKey = "RUNTIME", type = Type.NotEquals, envValue = "PRODUCT")})
public class TestMysqlHost implements MysqlHost{

    @Override
    public String getMysqlHost() {
        return "localhost";
    }
}
上一篇下一篇

猜你喜欢

热点阅读