Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Spring create instances of objects that are injected

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.

like image 814
Eager Learner Avatar asked Jan 18 '10 08:01

Eager Learner


1 Answers

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.
like image 133
skaffman Avatar answered Nov 15 '22 17:11

skaffman