@Produces @Named给出了WELD-001408

时间:2017-06-29 12:25:25

标签: java cdi weld

我试图了解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()]

1 个答案:

答案 0 :(得分:1)

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