How it works...
Consider running the TestBeans for either of the ch02-xml or ch02-jc projects. When all beans load eagerly, the result of the execution looks like this:
an employee is created. an employee is created. a department is created. a department is created. an employee is created. a department is created. an employee is created. a department is created. *********The empRec1 bean *************** *********The empRec2 bean *************** First Name: Juan Last Name: Luna Birthdate: Tue Oct 30 00:00:00 CST 1945 Salary: 100000.0 Dept. Name: History Department *********The empRec3 bean *************** First Name: Jose Last Name: Rizal Birthdate: Mon Jun 19 00:00:00 CDT 1950 Salary: 90000.0 Dept. Name: Communication Department *********The empRec4 bean *************** First Name: Diego Last Name: Silang Birthdate: Wed Dec 15 00:00:00 CST 1965 Salary: 85000.0 Dept. Name: Music Department
The preceding result shows us that all Employee and Department objects are created prior to their fetching stage. But once @Lazy or lazy-init="true" is applied to empRec4, for instance, there will be a change in the result:
an employee is created. an employee is created. a department is created. a department is created. an employee is created. a department is created. a department is created. *********The empRec1 bean *************** *********The empRec2 bean *************** First Name: Juan Last Name: Luna Birthdate: Tue Oct 30 00:00:00 CST 1945 Salary: 100000.0 Dept. Name: History Department *********The empRec3 bean *************** First Name: Jose Last Name: Rizal Birthdate: Mon Jun 19 00:00:00 CDT 1950 Salary: 90000.0 Dept. Name: Communication Department *********The empRec4 bean *************** an employee is created. First Name: Diego Last Name: Silang Birthdate: Wed Dec 15 00:00:00 CST 1965 Salary: 85000.0 Dept. Name: Music Department
The bean empRec4 was not pre-instantiated, rather its ApplicationContext loads and instantiates the object right after the getBean() method is invoked.
Whether to apply the eager or lazy mode on beans depends on the project requirement or specification. Usually, the eager bean loading method is applied to objects that need to be loaded at start-up due to faster request demands from its client applications. Or, some beans do not really consume more JVM space; thus, loading them at the container level will not compromise the project performance. There are also objects that are tightly wired to some other objects in the container and loading in lazy mode will cause a series of dependency errors and runtime exceptions.
On bean objects that consume many resources, which may cause performance issues during application start-up, it is advisable to apply the lazy loading method.