使用Arquillian JUnit(版本1.1.1和4.11)来设置嵌入JDK 1.7.25的CDI(Weld 1.1.13.Final上的1.0.0.CR7)....
获得以下课程:
public class Receiver {
private String message;
public void catching(@Observes DummyEvent event) {
System.out.println(String.format("message [%s], hash [%d]", event.getMessage(), hashCode()));
this.message = event.getMessage();
}
public String getMessage() {
return this.message;
}
}
public class Sender {
@Inject @Any
Event<DummyEvent> e;
public void fire(String message) {
System.out.println(String.format("fire message [%s], hash [%d]", message, hashCode()));
DummyEvent de = new DummyEvent;
de.setMessage(message);
e.fire(de);
}
}
@RunWith(Arquillian.class)
public class Example {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class).addClasses(Example .class, Receiver.class, Sender.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Inject
Receiver receiver;
@Inject
Sender sender;
@Test
public void dummy() {
System.out.println(String.format("sender hash [%d]", sender.hashCode()));
sender.fire("Hello from me");
System.out.println(String.format("message [%s], receiver hash: [%d]",
receiver.getMessage(), receiver.hashCode()));
}
}
打印的内容如下:
sender hash [785714873]
firing event [value: Hello from me], hash [785714873]
message [Hello from me], hash [632925108]
message [null], receiver hash: [1085786565]
我没有得到的是接收器哈希码不同的原因,并且事件未传播到示例JUnit中注入的Receiver bean。而是将事件发送到某个OTHER接收器bean。
这是否与范围有关(应该是默认的@Dependent)?
答案 0 :(得分:2)
看起来Receiver
和Sender
没有定义范围。结果,他们将@Dependent
作为他们的范围。当您使用@Dependent
时,会在每个注入点注入一个新实例。