java - 如何使用带参数的自定义注释查找 CDI bean?
问题描述
我有一个 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 的bean @MyType(init=true)
?
解决方案
You need create a class that extends AnnotationLiteral
and implements your annotation. An example is given by the documentation of 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; } };
In your case, it might look something like:
@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;
}
}
}
And then use it:
Instance<MyBean> configs = CDI.current().select(MyBean.class, DbType.Literal.INIT);
推荐阅读
- javascript - HMAC sha1 签名与 x-hub-signature 标头不匹配
- python - 如何判断一个ffmpeg子进程是否掉线
- java - 使用导航组件传递数据 - 当指南不需要时,我为什么需要构造函数的值?
- java - 当流式 DataFrames/DataSets 上存在流式聚合时不支持附加输出模式而没有水印
- python - 在 imshow-plot 上绘制单个像素的方法
- react-native - 显示带有禁用标题的箭头左后退按钮
- google-apps-script - 在谷歌工作表中选中复选框时如何插入日期和时间?
- automation - 使用多个浏览器的量角器测试在启动时失败
- java - Jacoco 报告没有考虑在 Maven 中进行 Cucumber 测试
- javascript - 有没有人类用户不能使用网站的方法?