I have a @TransactionScoped bean that is injected into a EJB enpoint. When i invoke the EJB via e.g. a JAX-RS endpoint, I can see that two instances of the bean are created. I am wondering out of interest, why this first bean instance might be created. It is happening on payara and wildfly.
@TransactionScoped
public class TransactionBean implements Serializable {
private String data;
private static AtomicInteger counter = new AtomicInteger();
public TransactionBean() {
this.data = "TransactionBean #" + counter.getAndIncrement() + " created.";
System.out.println("Created " + this.data);
}
public String toString() {
return data;
}
}
I see Output
The #1 instance is the one beeing used in the actual transaction. Why is this first instance created? Is it an implementation-detail of CDI in those particular app-servers or is it happening on purpose? It is just out of curiosity...
Cheers, Daniel
What you witness is most likely the creation of a proxy object.
CDI (Weld in your case, unless you changed Wildfly internals) will create the underlying object itself and the proxy which it will deliver to your injection points.
To verify this thought you may try a piece of code similar to your where you will use @Singleton
bean. There, the constructor should only be called once, as the @Singleton
does not create a proxy object.