我想执行以下操作来有条件地加载bean:
@Conditional(OnAuthoritieCondition.class, "SOME_INPUT_STRING")
但是,当我尝试实现这一点时,我得到以下信息:
public class OnAuthoritieCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return false;
}
}
现在我的问题是如何实现带有参数的自定义条件,或者有更好的方法来完成我想要的工作?
答案 0 :(得分:2)
创建自定义注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Conditional;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(value = CustomCondition.class)
public @interface ConditionalController {
String condition();
}
您的自定义条件
public class CustomCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalController.class.getName());
String condition = (String) attributes.get("condition");
return "GO".equalsIgnoreCase(condition);
}
}
使用方式
@ConditionalController(condition = "GO")