编程语言
首页 > 编程语言> > java – @Produces @Named给出了一个WELD-001408

java – @Produces @Named给出了一个WELD-001408

作者:互联网

我试图了解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,cdi,weld
来源: https://codeday.me/bug/20190705/1391113.html