OnPropertyCondition实现

4 篇文章 0 订阅

如果使用的是spring框架,OnPropertyCondition自定义实现

@Conditional({OnPropertyCondition.class})
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ConditionalOnProperties {

  String havingValue() default "";

  String[] keys() default {};

}
public class LoadProperties {

  private LoadProperties(){

  }
  
  private static Properties p = new Properties();

  public static String getValueByKey(String key)  {
    synchronized (p){
      if(p.isEmpty()){
        try {
          getProperties();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    if(p == null){
      return null;
    }

    String value = p.getProperty(key);
    return value;
  }
  
  private static void getProperties() throws IOException {

    InputStream f = LoadProperties.class.getClass().getResourceAsStream("/config.properties");
    p = new Properties();
    p.load(f);
  }

}
public class OnPropertyCondition implements Condition {

  @Override
  public boolean matches(ConditionContext conditionContext,AnnotatedTypeMetadata metadata) {
    List<AnnotationAttributes> allAnnotationAttributes = this.annotationAttributesFromMultiValueMap(metadata.getAllAnnotationAttributes(
        ConditionalOnProperties.class.getName()));
    for(AnnotationAttributes annota : allAnnotationAttributes){
      Spec s = new Spec(annota);
      String[] keys = s.keys;
      for(String key : keys){
        String val = LoadProperties.getValueByKey(key);
        if(s.havingValue.equals(val)){
          return true;
        }
      }
    }
    return false;
  }


  private List<AnnotationAttributes> annotationAttributesFromMultiValueMap(
      MultiValueMap<String, Object> multiValueMap) {
    List<Map<String, Object>> maps = new ArrayList();
    multiValueMap.forEach((key, value) -> {
      for(int i = 0; i < value.size(); ++i) {
        Map<String, Object> map;
        if (i < maps.size()) {
          map = (Map)maps.get(i);
        } else {
          map = new HashMap();
          maps.add(map);
        }

        ((Map)map).put(key, value.get(i));
      }

    });
    List<AnnotationAttributes> annotationAttributes = new ArrayList(maps.size());
    Iterator var4 = maps.iterator();

    while(var4.hasNext()) {
      Map<String, Object> map = (Map)var4.next();
      annotationAttributes.add(AnnotationAttributes.fromMap(map));
    }

    return annotationAttributes;
  }

  private static class Spec {
    private String havingValue;
    private String[] keys;

    Spec(AnnotationAttributes annotationAttributes) {
      this.keys = (String[])annotationAttributes.get("keys");

      this.havingValue = annotationAttributes.getString("havingValue");
    }

    private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
      int keyLength = keys.length;

      for(int i = 0; i < keyLength; ++i) {
        String key = keys[i];
        if (resolver.containsProperty(key)) {
          if (!this.isMatch(resolver.getProperty(key), this.havingValue)) {
            nonMatching.add(key);
          }
        }
      }

    }

    private boolean isMatch(String value, String requiredValue) {
      if (StringUtils.hasLength(requiredValue)) {
        return requiredValue.equalsIgnoreCase(value);
      } else {
        return !"false".equalsIgnoreCase(value);
      }
    }

    public String toString() {
      StringBuilder result = new StringBuilder();
      result.append("(");
      if (this.keys.length == 1) {
        result.append(this.keys[0]);
      } else {
        result.append("[");
        result.append(StringUtils.arrayToCommaDelimitedString(this.keys));
        result.append("]");
      }

      if (StringUtils.hasLength(this.havingValue)) {
        result.append("=").append(this.havingValue);
      }

      result.append(")");
      return result.toString();
    }
  }
}
@Service("Test1ServiceImpl")
@ConditionalOnProperties(keys="test.type",havingValue = "1")
public class Test1ServiceImpl  implements ITest1Service {

  @Value("${test.type}")
  private String type;

  @Override
  public void test() {
    System.out.println("Test1ServiceImpl:"+type);
  }
}
@Service("Test2ServiceImpl")
@ConditionalOnProperties(keys="test.type",havingValue = "2")
public class Test2ServiceImpl implements ITest1Service {

  @Override
  public void test() {
    System.out.println("Test2ServiceImpl");
  }
}

public interface ITest1Service {

  void test();

}

测试类

public class Test {

  public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
    ITest1Service t2 = (ITest1Service)applicationContext.getBean("Test2ServiceImpl");
    //ITest1Service t1 = (ITest1Service)applicationContext.getBean("Test1ServiceImpl");
    //t1.test();
    t2.test();
  }

}

config.properties 配置

test.type=2

spring-config.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">




  <bean id="propertyConfigurer"   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath:config.properties</value>
      </list>
    </property>
  </bean>

  <context:component-scan base-package="com.test">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
  </context:component-scan>

</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值