Can you explain better this concept from this video i'm watching "Instructor: In this…
- User
Can you explain better this concept from this video i'm watching "Instructor: In this video,
we're gonna cover lazy initialization.
Now by default, when your application starts,
all beans are initialized.
So it'll scan for all the components,
and all those components will be initialized.
So spring will create a new instance of each,
and make them available.
Now we can get some insights into this
by setting up some diagnostics,
or adding some println statements to our constructors.
So on our CricketCoach,
we'll add a println statement where we'll simply print
out the name of the class that we're processing on.
We'll do a similar thing here for baseball coach,
track coach, and also tennis coach.
And now, when we start our application,
then in the actual logs we should see In constructor:
BaseballCoach, PicketCoach, and so on.
Again, by the default when your application starts,
all beans are initialized and Spring will create an instance
of each and make them available.
Now we could make use of lazy initialization,
where instead of creating all the beans up front,
we can specify lazy initialization.
So, a bean will only be initialized in the following cases:
either when it's needed for a dependency injection,
or it is explicitly requested.
We simply add the lazy annotation
to a given class and those rules will come into play.
And here's a coding example: So for our track coach,
we'll say that our track coach is lazy,
(chuckling) so we'll make use of the lazy annotation.
This given bean will only be initialized
if it's needed for dependency injection.
If it's not needed, they won't create it.
In this coding example here,
with our demo controller and our constructor injection,
we're gonna inject the CricketCoach.
And when we run the application, we'll see the outputs
for our BaseballCoach, CricketCoach, and TennisCoach.
Since we're not injecting the TrackCoach
in this given scenario, then TrackCoach is not initialized.
So basically we're saying,
"Hey, don't create me unless I'm actually needed.
I don't wanna simply stand around and do nothing."
Now to configure the other beans for lazy initialization,
well, we'd need to add the lazy annotation to each class.
- Assistant