gpt4 book ai didi

java - 使用@Alternative Weld 不明确的依赖

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:09 26 4
gpt4 key购买 nike

我的一个类中有一个注入(inject)点

@Inject
private UsbServices usbServices;

还有一个带有 @Produces 的 Weld 类方法

public class AppProducer
{

@Produces
@Singleton
public UsbServices getUsbServices()
{
UsbServices usbServices = null;
try
{
usbServices = UsbHostManager.getUsbServices();
} catch (SecurityException | UsbException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return usbServices;
}

}

我希望在集成测试期间交换替代实现,所以我有上述类的替代版本

@Alternative
public class TestAppProducer
{

@Produces
@Singleton
public UsbServices getUsbServices()
{
return new UsbServicesSimulator();
}

}

还有下面我的测试包resources/META-INF里面的beans.xml

<beans xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<alternatives>
<class>xxx.TestAppProducer</class>
</alternatives>
</beans>

为了对此进行测试,我尝试使用它的主类启动 Weld 并手动连接一个 USB“设备”。测试方法有以下

Weld weld = new Weld();
WeldContainer container = weld.initialize();
PCSyncApplication app = container.instance().select(PCSyncApplication.class).get();
ServicesManager servMan = app.getServicesManager();
UsbServicesSimulator servSimulator = (UsbServicesSimulator) servMan.getUsbServices();
servSimualtor.attachDevice(new FakeDevice());

但是我得到了一个不明确的依赖异常

Exception in thread "main" org.jboss.weld.exceptions.DeploymentException: Exception List with 2 exceptions:
Exception 0 :
org.jboss.weld.exceptions.DeploymentException: WELD-001409: Ambiguous dependencies for type UsbServices with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private xxx.manager.ServicesManager.usbServices
at xxx.manager.ServicesManager.usbServices(ServicesManager.java:0)
Possible dependencies:
- Managed Bean [class xxx.simulator.usb.UsbServicesSimulator] with qualifiers [@Any @Default],
- Producer Method [UsbServices] with qualifiers [@Any @Default] declared as [[BackedAnnotatedMethod] @Produces @Singleton public xxx.AppProducer.getUsbServices()]

编辑:如果我对 UsbServicesSimulator 进行注释,则进行小更新随着以下消息消失

@Alternative
public class UsbServicesSimulator implements UsbServices

但我不确定我是否理解其中的原因。我会想到 TestAppProducer<alternatives>beans.xml够了吗?

最佳答案

使用@Alternative 注释,您只能禁用测试服务,而不能解决不明确的依赖关系。如果您想启用替代方案,则主版本不应在类路径中可见或应具有较低的优先级,例如@Priority 用 beans.xml 或 @Vetoed 注释或禁用。还有一些其他的技巧,
您可以在这里找到完整的文档 https://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#alternatives

我更喜欢使用单独的项目,或者使用 Arquillian 运行测试并在类路径中只包含我需要的那个类。在这种情况下,我不建议使用优先级。因为您需要为生产版本禁用或设置较低的优先级。

关于java - 使用@Alternative Weld 不明确的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com