【发布时间】:2016-09-11 07:57:05
【问题描述】:
有没有办法注入@Produces返回接口的具体实现?
SomeClassImpl implements SomeClass {
public Integer iField;
}
生产者类:
@Produces
public SomeClass produceChild(){
SomeClassImpl impl = new SomeClassImpl();
impl.iField = 17;
return impl;
}
消费类:
@Inject SomeClassImpl classImpl;
编辑
尝试@Inject SomeClassImpl 不会强制容器使用返回超类型SomeClass 的@Produces 方法。
为什么可以通过@Injectparent-type(没有Producer)注入child-type,但是没有变种通过@Producesparent-type注入child-type?
【问题讨论】:
-
如果您有多个接口实现,请使用qualifiers
-
关于您的编辑,因为您的
@Produces方法会生成SomeClass实例,而不是SomeClassImpl实例,它可以返回SomeClass的任何实现,而不仅仅是SomeClassImpl实例.您可以通过注入SomeClass(不是实现)并使用限定符来修复它,或者修改您的@Produces方法以返回SomeClassImpl。 -
我明白了,谢谢,但我需要通过 Produces 方法准确地注入 SomeClassImpl 类型。如果不可能 - 请告诉我“这不可能!” =))
标签: jakarta-ee interface cdi implementation producer