我正在努力了解CDI,在这种情况下,注释为@Produces
和@Named
我有以下代码
@RunWith(CdiRunner.class)
public class cdiTest {
@Inject
protected CDIModel em;
@Test
public void injectionTest(){
Assert.assertEquals("this", em.getMyString());
}
}
public class CDIModel {
String myString;
public CDIModel(String myString) {
this.myString = myString;
}
public String getMyString() {
return myString;
}
}
public class EntityProducer {
@Produces
@Named("this")
@Singleton
public CDIModel doThis() {
return new CDIModel("this");
}
@Produces
@Named("that")
@Singleton
public CDIModel doThat() {
return new CDIModel("that");
}
}
我为什么得到
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied
dependencies for type CDIModel with qualifiers @Named
at injection point [UnbackedAnnotatedField] @Inject @Named protected
persistence.dao.cdiTest.em
at persistence.dao.cdiTest.em(cdiTest.java:0)
添加@AdditionalClasses(EntityProducer.class)后,我得到
org.jboss.weld.exceptions.DeploymentException: WELD-001409: Ambiguous
dependencies for type CDIModel with qualifiers @Default
at injection point [UnbackedAnnotatedField] @Inject protected
dk.nykredit.lanc.persistence.dao.cdiTest.em
at dk.nykredit.lanc.persistence.dao.cdiTest.em(cdiTest.java:0)
Possible dependencies:
- Producer Method [CDIModel] with qualifiers [@Default @Named @Any] declared
as [[BackedAnnotatedMethod] @Produces @Named @Singleton public
persistence.dao.EntityProducer.doThat()],
- Producer Method [CDIModel] with qualifiers [@Default @Named @Any] declared
as [[BackedAnnotatedMethod] @Produces @Named @Singleton public
persistence.dao.EntityProducer.doThis()]
最佳答案
CDI-Unit不会扫描所有类,因此不会了解EntityProducer
类。因此,您必须手动添加要由CDI扫描的类/程序包。
您可以使用@AdditionalClasses
批注:
@RunWith(CdiRunner.class)
@AdditionalClasses(EntityProducer.class)
public class cdiTest {
....
....
}
编辑
然后,您得到了一个模糊的依赖关系,因为您没有适当地限定您的注射质量。您应该在测试类中使用
@Named("this")
或@Named("that")
:@Inject
@Named("this") // or @Named("that")
protected CDIModel em;
另请注意,在CDI中,我们通常使用
@Qualifier
而不是@Named
关于java - @Produces @Named给出WELD-001408,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44825105/