Spring IOC Container wires the dependencies among the beans and returns the fully built bean tree to the caller. Every time, not fully built bean tree is used by the caller, only portion of it is used. Thus a significant portion of the built objects goes for garbage collection. This results in an unwanted memory consumption and CPU consumption (for bean creation and GC).
Suppose say in the bean definitions (see below figure), following objects are defined. During run-time, if caller requests for Object A, then Spring Factory would wire all the dependencies (i.e. B, B1, B2, C, C1, C2, D, D1, D2) and return the Object A to the caller.
During runtime, depending on the data condition only a branch of the object tree will be exercised (in our application, could be the case in other applications as well), i.e. Objects C, C1, C2 will only be exercised. Objects B, B1, B2, D, D1, D2 will not be exercised. So for this transaction objects B, B1, B2, D, D1, D2 are created and destroyed without a purpose. This results in unwanted memory utilization and CPU utilization (in creating and doing GC). The problem compounds dramatically when there are several immediate dependents to A (which is typical in our case).
It would be ideal if Spring IOC Container can just create A when caller requests for it and during the run-time, A should create B or C or D, based on which object is needed during runtime (based on data condition). Currently we are managing this dependency within our application code (basically within A). In our bean definitions we don’t wire in B or C or D. During runtime when A has decided which path to pursue, then we create the appropriate object and give it to A.
It would be ideal if it can be managed by Spring IOC container, by exposing some kind of attribute in A’s bean definition (example: lazy-load-dependents=”true”).