[英]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 >() {});
将同时返回两个bean。
如何在我的CDI.current()。select()中指定我只想要带有限定符@MyType(init=true)
bean?
您需要创建一个扩展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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.