如何使用带参数的自定义注释查找 CDI bean?

How to find CDI beans with a custom annotation with parameters?

我有一个 Wildfly 10 应用程序,我在其中创建了自定义 @Qualifer 注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface DbType {
    /**
     * If this DbType is part of the initialization process for an existing DB
     */
    boolean init() default false;
}

然后我有几个生产者方法:

@Produces
@DbType
public MyBean createBean1(){
  return new MyBean();
}

@Produces
@DbType(init=true)
public MyBean createBean2(){
  return new MyBean(true);
}

在我的代码中,我想以编程方式检索具有给定注释的所有 bean,但不确定如何。

    Instance<MyBean> configs = CDI.current().select(MyBean.class, new AnnotationLiteral<DbType >() {});

将 return 两个豆子。

如何在我的 CDI.current().select() 中指定我只想要具有限定符 @MyType(init=true) 的 bean?

您需要创建一个 class 来扩展 AnnotationLiteral 并实现您的注解。 AnnotationLiteral:

的文档给出了一个例子

Supports inline instantiation of annotation type instances.

An instance of an annotation type may be obtained by subclassing AnnotationLiteral.

public abstract class PayByQualifier extends AnnotationLiteral<PayBy> implements PayBy {
}

PayBy payByCheque = new PayByQualifier() {
    public PaymentMethod value() {
        return CHEQUE;
    }
};

在您的情况下,它可能类似于:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface DbType {
    /**
     * If this DbType is part of the initialization process for an existing DB
     */
    boolean init() default false;

    class Literal extends AnnotationLiteral<DbType> implements DbType {

        public static Literal INIT = new Literal(true);
        public static Literal NO_INIT = new Literal(false);

        private final boolean init;

        private Literal(boolean init) {
            this.init = init;
        }

        @Override
        public boolean init() {
            return init;
        }

    }

}

然后使用它:

Instance<MyBean> configs = CDI.current().select(MyBean.class, DbType.Literal.INIT);