如何在注释的基础上选择cdi java bean,那么注释就构成了参数表?
这个问题用一个例子来说明比用一个例子来描述更容易。
假设对于每个类型的对象
问题
我们必须选择适当的解决办法。
public class Problem {
private Object data;
private ProblemType type;
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public ProblemType getType() { return type; }
public void setType(ProblemType type) { this.type = type;}
}
有几种类型的问题:
public enum ProblemType {
A, B, C;
}
解决方案很少:
public interface Solution {
public void resolve(Problem problem);
}
喜欢
第一个解决方案
以下内容:
@RequestScoped
@SolutionQualifier(problemTypes = { ProblemType.A, ProblemType.C })
public class FirstSolution implements Solution {
@Override
public void resolve(Problem problem) {
// ...
}
}
和
第二种解决方案
以下内容:
@RequestScoped
@SolutionQualifier(problemTypes = { ProblemType.B })
public class SecondSolution implements Solution {
@Override
public void resolve(Problem problem) {
// ...
}
}
应根据注释选择解决方案
@解决方案限定符
以下内容:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SolutionQualifier {
ProblemType[] problemTypes();
public static class SolutionQualifierLiteral extends AnnotationLiteral<SolutionQualifier> implements SolutionQualifier {
private ProblemType[] problemTypes;
public SolutionQualifierLiteral(ProblemType[] problems) {
this.problemTypes = problems;
}
@Override
public ProblemType[] problemTypes() {
return problemTypes;
}
}
}
由
解决方案提供者
以下内容:
@RequestScoped
public class DefaultSolutionProvider implements SolutionProvider {
@Inject
@Any
private Instance<Solution> solutions;
@Override
public Instance<Solution> getSolution(Problem problem) {
/**
* Here is the problem of choosing proper solution.
* I do not know how method {@link javax.enterprise.inject.Instance#select(Annotation...)}
* works, and how it compares annotations, so I do no know what argument I should put there
* to obtain proper solution.
*/
ProblemType[] problemTypes = { problem.getType() };
return solutions.select(new SolutionQualifier.SolutionQualifierLiteral(problemTypes));
}
}
最后一个问题是:
我不知道怎么做
javax.enterprise.inject.instance select(annotation…)
内部工作,以及它如何比较注释,所以我不知道我应该放在哪里,以获得适当的解决方案。如果出现类型问题
一个
桌子
问题类型[]
将由一个参数组成,而
FirstSolution.Class类
用注释
@解决方案限定符
有两个参数,所以我不能得到正确的实例。