我有两个类,我想注入:
@ApplicationScoped
public class BeanThing {
public String apply(String s) {
return "bt(" + s + ")";
}
}
和
@ApplicationScoped
public class ClassFunction implements Function<String, String> {
@Override
public String apply(String s) {
return "cf(" + s + ")";
}
}
当我尝试在其他地方使用它们时,我会得到不同的行为:
Set<Bean<?>> functions = beanManager.getBeans(Function.class);
for (Bean<?> untyped : functions) {
Bean<Function<String, String>> typed = (Bean<Function<String, String>>) untyped;
Function<String, String> function = beanManager.getContext(typed.getScope()).get(typed, beanManager.createCreationalContext(typed));
System.err.println(function.apply("beanManager"));
}
Set<Bean<?>> beanThings = beanManager.getBeans(BeanThing.class);
for (Bean<?> untyped : beanThings) {
Bean<BeanThing> typed = (Bean<BeanThing>) untyped;
BeanThing beanThing = beanManager.getContext(typed.getScope()).get(typed, beanManager.createCreationalContext(typed));
System.err.println(beanThing.apply("beanManager"));
}
System.err.println(injectedFunction.apply("injected"));
System.err.println(beanThing.apply("injected"));
System.err.println("injectedFunction is a function: " + (injectedFunction instanceof Function));
我的输出是:
bt(beanManager)
cf(injected)
bt(injected)
injectedFunction is a function: true
这比我预期的少一行。
有人可以解释这里发生了什么吗?
解决方案,感谢 Siliarus 让我走上正确的道路:
Set<Bean<?>> functions = beanManager.getBeans(new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[]{new WildcardType() {...}, new WildcardType() {...};
}
@Override
public Type getRawType() {
return Function.class;
}
});