1. 创建注解
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Conditional(ConditionOnMultiValuesImpl.class)
public @interface ConditionOnMultiValues {
String value();
String expectValue();
}
Conditional 指定实现类,实现类需实现org.springframework.context.annotation.Condition
2. 实现Condition
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;
import java.util.List;
import java.util.Objects;
@Slf4j
public class ConditionOnMultiValuesImpl implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ConditionOnMultiValues.class.getName());
System.out.println(metadata);
System.out.println(attrs);
if (attrs != null) {
String value = findFirst(attrs.get("value"));
String expectValue = findFirst(attrs.get("expectValue"));
String realValue = context.getEnvironment().getProperty(value);
if (StrUtil.isBlank(realValue)) {
return false;
}
return realValue.contains(expectValue);
}
return true;
}
private String findFirst(List<String> list) {
if (Objects.isNull(list)) {
return null;
}
return list.get(0);
}
}