When does Spring create instances of objects that are injected

dependency-injection, java, spring

Solution

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` or `session`), using the `scope="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.

Problem

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.

Original source