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

问题描述 投票:0回答:1

我有一个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 >() {});

将返回两个bean。

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

java dependency-injection cdi weld
1个回答
2
投票

您需要创建一个扩展AnnotationLiteral的类并实现您的注释。 AnnotationLiteral的文档给出了一个例子:

支持注释类型实例的内联实例化。

可以通过继承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);
© www.soinside.com 2019 - 2024. All rights reserved.