2.4.2.3.1)、通过SpringBoot自带的注解ConditionalOnProperty实现
#bean实例化条件配置项
conditionKey: 1.0
ManageImpl1.java代码如下:(MyManage接口、ManageImpl2省略)
package com.dxz.palmpay.condition; import javax.annotation.PostConstruct; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; //仅当conditionKey==1.0的时候实例化这个类 @ConditionalOnProperty(name = "conditionKey", havingValue = "1.0") @Component public class ManageImpl1 implements MyManage { @Override public void sayHello() { System.out.println("我是实现类01"); } //为了效果,创建后打印一些信息 @PostConstruct public void init() { this.sayHello(); } }
2.4.2.3.2)、自定义条件注解
(1)思路
- name:String类型,用来接受application.properties的配置项的key
- havingValue:String数组类型,用来和name对应key的Value进行匹配
(2)定义注解
package com.dxz.palmpay.condition; import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(CustomOnPropertyCondition.class) public @interface CustomConditionalOnProperty { String name() default ""; //havingValue数组,支持or匹配 String[] havingValue() default {}; }
(3)定义注解的匹配规则
package com.dxz.palmpay.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; /** * 自定义条件注解的验证规则 */ public class CustomOnPropertyCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { Map<String, Object> annotationAttributes = annotatedTypeMetadata .getAnnotationAttributes(CustomConditionalOnProperty.class.getName()); String propertyName = (String) annotationAttributes.get("name"); String[] values = (String[]) annotationAttributes.get("havingValue"); if (0 == values.length) { return false; } String propertyValue = conditionContext.getEnvironment().getProperty(propertyName); // 有一个匹配上就ok for (String havingValue : values) { if (propertyValue.equalsIgnoreCase(havingValue)) { return true; } } return false; } }
@Component @CustomConditionalOnProperty(name = "db.version", havingValue = {"3"}) public class ManageImpl3 implements MyManage { @Component @CustomConditionalOnProperty(name = "db.version", havingValue = {"1","2","4"}) public class ManageImpl4 implements MyManage {
自定义Condition注解,主要就2步
(1)定义一个条件注解(2)定义一个条件的校验规则