Reputation: 31
I use CDI (Weld) in Java SE application. I made a Bean let's call it BeanA.
public class BeanA {
@PostConstruct
public void init() {
System.out.println("INIT");
}
public void receive(@Observes String test) {
System.out.println("received: " + test);
}
}
In my test method I invoke:
Weld weld = new Weld();
WeldContainer container = weld.initialize();
Instance<BeanA> instance = container.instance().select(BeanA.class);
BeanA bean = instance.get();
container.event().fire("TEST");
container.event().fire("TEST");
container.event().fire("TEST");
container.event().fire("TEST");
Why output is like? Why @PostConstruct is called everytime event is received?:
INIT
INIT
recived: TEST
INIT
recived: TEST
INIT
recived: TEST
INIT
recived: TEST
Upvotes: 0
Views: 719
Reputation: 279890
This is because the default scope of beans is @Dependent
. This means that every time you fire an event, a new instance of your observer bean needs to be created so that the even gets sent to it. @PostConstruct
gets invoked as part of that creation.
Annotate your BeanA
type with @Singleton
to set its scope to singleton. Only one will ever be created for your container.
Upvotes: 6