Spring does DI and creates objects so that your program need not worry of creating objects. But the question here is when an instance of injected object is created. Is it when the main program makes use of the instance or at the time an instance of main program is created.
All beans in the context are instantiated, injected and initialized when the context starts up. By the time the first bean has been retrieved from the context, all beans are ready for use.
There are two things that can prevent a bean being initialized at context start up:
- A bean has bean configured with a different scope (such as
prototype
,request
orsession
), using thescope="xyz"
attribute - A bean has been marked with
lazy-init="true"
, in which case it will only be instantiated when it's explicitly asked for, or if it's required as a dependency of some other bean.
By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
In a comment, the OP writes:
So it is up to the programmer to decide whether a bean needs to be lazily initialized or initialized upfront. This could be very subjective, but could you let me know about any best practices followed in this kind of situations.
Yes, it is up to the programmer (or system integrator) to decide.
There aren't really any "best practice" rules for deciding. Think of it this way:
If you declare a bean as lazily initialized when it will always need to be instantiated, you will possibly make the startup process slower.
If you declare a bean as eagerly initialized when it is not always needed, you will make the startup process slower, and possible use more memory. In the worst case, creating the unnecessary bean may even cause startup to fail.
In short, you need to understand your application.