The first creation is the container creating a scoped proxy of your bean. The scoped proxy is an object that extends your bean and gets injected whenever some other component needs your bean. It's methods however do not execute the real logic, rather delegate their execution to the correct contectual instance of your bean. An example will clarify:
Assume 2 requests, R1, R2. There must be 2 instances of ChartBean
, B1 and B2. Say another component, C, depends on ChartBean
. The relevant field of C must be injected with an instance of ChartBean
at application init time and call the correct bean instance at execution time. BUT at app init time there is no request and certainly no B1, B2. What does the container do? It creates the scoped proxy and injects it to whoever needs it. Then, whenever ChartBean.method()
is called, it is called on the proxy who decides which is the correct bean to call (B1 for R1, B2 for R2, throw exception if no request is active, e.g. called from a MessageDrivenBean
).
Having said the previous: DO NOT RUN BUSINESS LOGIC IN CONSTRUCTORS IN JAVA EE COMPONENTS, because constructors may be called from the system/container. Use a @PostConstruct
method instead:
...
public class ChartBean implements Serializable {
public ChartBean() {
// only construction logic here
}
...
@PostConstruct
void postConstruct() {
createCategoryModel();
createLinearModel();
}
}
By the way you can verify that the constructor is called from a proxy implementation by printing the class name in the constructor:
public ChartBean() {
System.out.println("ChartBean as " + this.getClass().getName());
}
The first time it gets called, it will be some other class than your own.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…