如何动态选择具有多个注解的bean

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

假设我有几个处理器类,每个处理器都能够处理一个或两个特定的键。我正在读取一个由 csv 行组成的文件,每一行在其中一个字段中都有一个键。 然后在解析文件的过程中,我在做:

class Parser(){
@Inject
    @Any
    Instance<Processsor> processors;
(...)
while (null != (text = reader.readLine())) {//let's say we got a reader before this loop
      String key = getKeyFromLine(text);
      Processsor selectedProc = processors.select(new ProcessorQualifier(key)).get();
      selectedProc.processLine(text);
   }
}

ProcessorQualifier 就像:

public class ProcessorQualifier extends AnnotationLiteral<ProcAnnotation> implements ProcAnnotation {
    private ProcTypeEnum type;

    public ProcessorQualifier(ProcTypeEnum type) {
        this.type = type;
    }

    @Override
    public ProcTypeEnum procTypes() {
        return this.type;
    }
}

只要我的处理器只有一个注释,这就可以完美地工作:

@ProcAnnotation(type=key1)
class Key1Processor implements Processor{
    void processLine(String text){
        ...
    }

但是如果我想让我的 Key1Processor 被选为 key1 OR key2 那么我不知道该怎么做。 如果我在类处理器上放置 2 个注释:它不会编译

Duplicate annotation of non-repeatable type @ProcAnnotation. Only annotation types marked @Repeatable can be used multiple times at one target.

然后我创建了一个 Repeatable 注释:

@Retention(RUNTIME)
@javax.enterprise.inject.Stereotype 
@Qualifier
@Target({ TYPE })
@Dependent
public @interface ProcAnnotations {
    ProcAnnotation[] value();
}

但我被卡住了,因为我不知道如何选择 (

processors.select(???)
) 其密钥之一与文本中解析的密钥匹配的处理器。 但据我所知
processors.select(new ProcessorQualifier(key))
遍历
Processors
的所有实例并选择与其注释匹配的实例
ProcessorQualifier
那么问题是
ProcessorQualifier
有/写?更一般地说,如何通过其限定符之一动态选择 bean?

java annotations cdi quarkus
© www.soinside.com 2019 - 2024. All rights reserved.