Spring boot: Bean and its Lifecycle | Inversion of Control (IOC)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to concept and coding this is Shan and today we are going to cover a very important topic in spring board that is Bean so in the previous four topics we have used couple of times that this is been this is been but we will cover in depth today so in a simple term if I have to Define Bean then I call it Bean is a Java object which is managed by a spring container that is iOS C inversion of control container okay so it's no different than Java object but only managed by Spring and what is ioc container ioc container contains all the beans which get created and also manage them so creation initialization and complete end to endend managing their life cycle right that is done by ioc okay so how to create a bean so there are two ways to create a bean one is through adate component annotation and another is through at theate Bean annotation with both ways you can create a bean but there are some specific use cases where you have to use ad theate be annotation using this might not help you for those use cases okay and what are those use cases I will tell you soon so let's first start with at the rate component annotation so at theate component annotation follows convention over configuration approach what does it mean so check this very simple example which I have created here a very simple class user with username and email and it's getter and Setter very basic class and I have put at theate component at top now this will tell spring boot hey you have to create its object you have to manage its life cycle right so that's the work of the component so component is convention over configuration what does it means so a spring boot when it try to create an object of it it uses some Auto configuration like hey if I have to uh create its object call it's default Constructor and then with using that we can create its object right because we are not providing any external configuration that and telling springboard that how you should create an user object no we haven't provided any configuration at theate component spring boot automatically use some its autoconfigure that okay I will use default Constructor to create its object okay at theate controller at theate service all are internally tell spring to create bean and manage it because if you see here atate controller if I am putting so at theate controller also internally is nothing but component also right it is also a component similarly service atate repository or are performing some specific task plus also they are component so all telling the spring that you have to create an object of it and manage its life cycle okay so this example is very simple right but now consider this example what would happen to this again same user class but only difference is now I have created one specific Constructor now you know that when we provide our own Constructor Java will not add default Constructor here now default Constructor is not present here okay so if I put at theate component means I am telling spring boot to create its object now spring boot has it autoconfigured that okay I have to call its default Constructor now when when it will try to create its being when it will try to create its object will it be able to create no because there is no default Constructor here and spring doesn't know what to pass in the username and email so when you will try to start an application your application will actually fail that not able to create a beam so what to do in this case you have to tell spring boot that hey when you create a user object pass this username this email right then only you would be able to create it because there is no default Constructor it so that's where at theate Bean annotation can help right so atate Bean comes into the picture where we provide the configuration details so like external configuration and tells the springboard to use it while creating a bean so this is how we do it so here if you see that first from the user class I have removed the at theate component now it is not needed okay the same example where there is no default Constructor now see this is how you create a configuration file so first create a class provide any name and use this annotation at the rate configuration at theate configuration annotation tells the spring boot that hey in this class you will find certain Bean methods right for that you have to create Bean also right so here we can provide at theate Bean on a method so you can use any method name so I've given a name like create user Bean because I want to create a user so I just given a name create user Bean you can provide anything return type is important so okay so return type is user it has to create this object so now here I'm telling springbot that how you should create its object so I'm telling create like this new user pass this username default username default email now what would happen is so whenever a spring tried to create an object of this user now it will not use Auto configuration why because we have provided the external configuration now suppose let's say you can ask me that hey what would happen Shan if I provide atate component here also means one way I'm telling uh spring to use Auto configuration but in the external configuration also I have provided the bean and telling spring to use this now let's say there is something called default Constructor also here present so which one it will use so first priority will goes to this one you can try it out right uh so you can create this uh object and after that try printing system do do do print lent and you can see which one actually spring boot uses to invoke right so this should get first priority external configuration because this is what we are providing right and what we want that is first priority to Spring boot not Auto configuration okay so now you understand like uh there is certain specific use cases where at theate Bean only can help you and this is one of the use case let's say where default Constructor is not present then you have to provide the how to create an object using at theate Bean annotation so also there is one more uh question can come that okay what if I have multiple atate Bean methods where I'm creating a same user let's say create user Bean one create user Bean 2 both returning user so what would happen here so generally in this case what generally happen is spring boot goes one by one and create a bean for all so in this case two object would get created like Bean one being two so one get created for this user also another is another for this user but with this information default username default email default username default email and another is another username and another email right and both now is going to manage by ioc okay so no matter how many times you write it a spring boot will create that many objects for it and which want to use that we can see later there are something called at theate qualifiers right or at theate you can provide a name to the bean and tell in your code thaty I even there are multiple objects I want to use this specific object that we will see different later okay but first concentrate on that how you can create a bean through atate component and through ad theate be so there are further two questions again comes to our mind that okay sh I know how to create a bean now right but how spring boot find these beans because I have a huge application code base and there are like thousands of file and I have written at theate component at let's say 50 60 files and also I have at the rate configuration file right where I have provided at the rate be so how actually is spring boot able to find this classes where it has to create a beam and another question is at what time these beans get created right so like as soon as you write it does it created like when Java compiles or what at what time is beans get created so that is another question which get asked so let's first focus on the first part how spring boot find this Bean so there are two ways one is at theate component scan annotation so at theate component annotation tells a spring boot to look in a specifi specified package and subpackage and look for all this annotated classes like at theate component atate service atate repository atate controller as I already told you that these annotations are also nothing but component two right so spring boot will look look for all these annotations in the specified package and subpackage and then it able to find those beans so let's say this in the in this class a spring boot application where we have a main you can write this at theate component scan and provide a base package now spring boot goes start from this and further sub packages so this Plus subpackage and look for this annotations now even if you don't provide this as in the I think starting video I also tell you that spring boot application also has atate component scan internally so if you see that spring boot application also has adate component scan and its Auto configuration is that start from the package where this class is present so it will start from the package where this class is present and go further sub classes sub packages okay so first way is through atate component scan and another way is through atate configuration so spring boot also looks for hey do you have any at theate configuration class present so it will look for those right and if it found that one then it will use all those at theate B which you have defined and just remember one thing atate configuration is also a atate component right so we can see that also annotation at theate configuration so at theate configuration is nothing also but component itself so whatever the package you have defined either you have defined or spring boot autoc configure has been taken so in that package it also looks for at theate configuration class and once it find the at theate configuration class it uses these beans also so whatever the bean method you have provided it will also collect it and create a bean for those so these are the two ways at theate component scan and at theate configuration spring boot finds the classes for which Bean has to be creation created and the second one is at what time these beans get created at what time these beans get created so the answer should be like in two ways the first one is eager initialization eager initialization means at the time we start our application that only that at that time itself beans get created another answer is lazy not at the time of uh application startup but whenever it is actually needed only that time it is created so there are two ways or you can say that two time this be get created so there are certain called scope I will cover it in the next part like there are different types of scope single turn scope prototype scope right so just for now you need to uh understand that what is eagerness so just wanted to tell you that beans with single turn Scopes are eagerly initialized right so don't worry about hey what is singlet turnon scope we will cover in depth later but for now you have to focus on this eagerness or lazy part just say that this is just an example that single turn scope beans are eagly initialized means at the time of application startup similarly uh beans with the Scopes like prototype they are lazy lazily initialized right means they are initialized when they actually not need it not at the time of application or another way is that even though it's a single turn but if you have used a specifically tell and uh springboard that at the rate lazy means you have to initialize it lazily right so here if you see that I haven't provide anything at the rate scope whether value is like your prototype or single turn if you haven't provideed anything by default it's single turn we will see later in depth but just for this I haven't provide anything at the rate scope means by default spring boot do autoconfigure and it will considered as single turn but now specifically I have used this annotation at theate lazy and telling springboard that hey don't create this object of this at the time of application startup whenever it is required then only create it so these are the two ways through which beans get created you will get better understanding now with this life cycle of being and most of things will get clear cleared because I will tell you with an example also with demo so now here this is the life cycle of a being so first time when you create an start an application so when you start an application what internally springboard will do it will also invoke the ioc inv verion of control now ioc what it will do is it will scan for the Bean search for the bean and how it will search for the Bean two ways through at theate component scan and atate configuration so it will use this to and look for all the beans it has to create and after that it will construct the bean like if it is eagerly has to be initialized it will create it if some beans wanted or required even though it is lazy it will invoke it right so at this third step it will construct the beans which is required fourth step is inject dependency into the constructed beans for example this is an object user and there is another class order okay so now let's say that uh this user has dependency on this order class order object so this user needs this order and let's say this is even lazy initialized or something now first third step was construct a bean so now let's say that this is singl turn means it can be eagerly initialized so what it will do is ioc will create an object of it so user object is created user object is created mean user Bean is created which ioc is managing now fourth step was inject dependency into the constructed Bean so whatever the bean is constructed now we'll inject that dependency so this user Bean has dependency on order so now what it will do is it will create the order object and injected here injected here so this is done at the fourth step fifth step is that now your bean is fully constructed it was created and after the dependencies also get injected into it now it is ready to use before it ready to use if you have to perform any task you can use at the post construct now ultimately Bean is into action you can use it you can use it to call its method method you can use it in your application now finally Bean is about to destroy and if you have to perform any task before it actually get destroyed you can write it here and ultimately Bean got destroyed okay so we will see it one by one like step one when you are starting an application okay so now let's say that when you are starting an application so during I told you that during application startup what springb will do it will invoke ioc so here I have taken a locks here so when you start a spring boot application you will see this two lines embedded web application context initializing spring embedded web application context initialization completed this is nothing but the ioc this is application context right this is the implementation of ioc Logics what ioc does we say that ioc manage all the beans so that application context does it so now when you start an application here if you can uh see that it has initialized the ioc and ioc work is to First scan the beans through at theate component scan annotation it will look for it and also at theate configuration it will scan all the beans and we'll try to construct it so at the step one during application startup spring boot invokes ioc container here application context provide the implementation for ioc now ioc container make use of at theate configuration and at theate component scan to look out for the classes for B Be need to be created your step two is construct the beans right so just see this example I have created a simple class user and just default Constructor and just printing initializing user now here if you see that I have put at theate component means I am telling spring boot to create its object and also you will see that I haven't provided anything at the rate scope means by default what would be the scope for this class single turn if it is single turn then means it is eligible for eager initialization or eager initialization means during application startup itself ioc will create its object create is beam so here if you see that I started the server ioc got involved when ioc got invoke it does atate component scan and atate configuration it is able to find this class now it will see that creating its object default instructor is called initializing user so it created The Bean of this okay so second step is once you start an application ioc started look for the bean and it will construct the bean of those classes which can be eagerly initialize like single turn so once the bean is created the The Next Step would be your bean is created The Next Step would be dependency injection so see this one see this example so I have created a very simple class user and it's Constructor initializing user system. Prine right and I have put at theate component here means spring has to create its object and also there is no at theate scope means it's single turn applicable for eager initialization and I have put one now dependency that hey user is depend on this order right now here if you see that I have created an order class very simple class one Constructor default Constructor with like initializing order also I have put at theate component means the spring Bo has to create its object and if you see there is no at theate scope means this a single turn eligible for eager initialization but now I have specifically put at the rate lazy means I'm telling spring boot not to create its object at the time of application startup so now what would happen so this is very basic class I have created now I have started the application when I started the application ioc initialize it will look for the beans it find this Bean user bean and it will find these classes user class where at theate component is there it will also find order class at theate component is there now it will see that hey your order class is marked as lazy initialized so I don't have to initialize is during application startup only when it is needed I have to create it so your iOS will try to create first its object user so it will call initialize user done now after the bean is constructed what it will do next step is try to inject the dependency so now it will look that hey this annotation at theate Auto so it will with this annotation what is spring board says that hey is this Bean already present in container in ioc container does order Bean is already present if yes it will just inject it and we can use it if no then what would do is ioc Will first create order Bean means it will first create order object right and then inject into this So currently order object is not even constructed right so means ioc will have to now create first order object so means this is required so it will it Constructor will get invoked initializing order now it will inject into it now the order object which is constructed now it is getting initialized here okay but if this is not present if this dependency is not present let's say this is not present and then you start an application you will see that okay user is initialized right and there is no dependency you won't find this you won't find this why because at application startup this is marked as lazy order so it will not be initialized at the time only when it is needed since we have put a dependency here in the user means it is needed for the user Bean so that's why order object is also initialized okay but this step is clear right after the construction of the bean dependency injection happens through the help of Auto so there is uh another thing that there are different ways of doing an injection construction injection Setter injection field injection we will cover each injection in depth in the next part with the scope I will cover this uh dependency injection also but you already know dependency injection right uh it uses this atate autoi anotation so first it will check if Bean is already present use it don't create new Bean of this if Bean is not found then only spring will create it and inject it so this injection there are three logic which we will see later okay now your user object is now fully constructed now it is ready to use but before ready to use if any pre task you have to do you can do through at the rate post construct annotation so here very simple user class marked as atate component again like previously it has dependence an order this is a sample base Constructor initializing user but now I have written this class which is marked as atate post construct and you can give any name and I've just printed that bean has been constructed and dependencies has been injected to only after that this will get involved now if you start the application ioc started ioc able to find this class that it has to create its object and it is single turn eligible for uh eager initialization so it will create initializing user it will call its Constructor after that it will inject look for any dependency injection so Auto wired it it has dependency on order order Bean is present let's say no so it will invoke the order so order like initializing order and will update it now your bean is ready after that it will invoke at theate post constru so now it will print this okay so that's the sequence so you can do any uh pre-task like if you want to do any logging you can do it here or if you want to initialize something you can do it here like any map hash map something you want to put anything some data you can initialize it here before using it now at fifth step you can say that the bean actually you use start using it so in this step I'm talking about uh post construct happen now actually you are actually using the bean so you now you have a user object let's say now you're calling that user object do some method you are actually using it in your application that's what I mean use the bean now once the bean has been constructed also now it's time for is to get destroyed but before it getting destroyed you have to do some pre-task like okay before it actually destroyed I have to release all the resources so you can use this atate P destroy annotation so before the bean actually get destroyed this method will get invoked let's say you have a DB connection and you before Bean get destroyed you have to make sure that yes DB connection is uh released no resources uh hold so you can check it in this so now again if you see that very simple class user no dependencies is there right at theate post construct pre destroy have written now when you start an application generally this is the main class which is present into this when you start an application your ioc started right so this is also you will get a context object ioc application context object right so here I'm catching it and specifically closing it right I am specifically closing it generally you don't have to close all right so but I here for the testing purpose to show you I'm specifically closing it so what would be the flow when I start this application first ioc will start when ioc will start so it's running right when ioc will start it will find this Bean it's a single turn eagerly initialize eligible so it will initialize the user then it look for any dependency no dependency means now object is fully constructed user now it will do Post construct so post Constructor initiated will get printed now you can uh so this one happen so now your object is ready to use but as soon as it ready to use we are now closing it the next step so now when we are closing the application context means when we are closing the container all the beans which are present inside this will also get destroyed so it will call for Speed destroy method on those beans right in each classes if you have any uh pre destroy so that would get invoke for each Bean right in a specific classes beans so now Bean is about to destroy and pre- Destroy method for this user Bean so this will get involved Bean is about to destroy and pre destroy method and ultimately your ioc will get closed okay so we have covered till this all your whole life cycle of a bean is get completed also I hope that clarifies you a lot at what time Bean get created what actually Bean is and but the next topic we will cover is your dependency injection Auto we have already seen what it does but different type of injection we have to see very important right construction injection very important we used a lot like in the industry and the scope of the be Bean very important too right so this is one more property which I will cover that qualifier when you have more than one bean for the same typ that I told you right if you have more than one bean for this user user user which which Bean to use in your code you bean name and qualifier help you to choose that I want to use this object so this three part I will cover next okay team if you have any doubt in this this is very important topic in the life cycle part eagerness lazy initialized part right and do try it out with your hands like uh then only you will get more questions and then we can discuss further okay guys thank you see you soon
Info
Channel: Concept && Coding - by Shrayansh
Views: 23,851
Rating: undefined out of 5
Keywords: Spring bean, Spring bean lifecycle, Inversion of Control, spring annotations, Component vs Bean annotation, What is Bean, How to Create Bean, ComponentScan annotation, Eagerly Initialized and Lazy-initialized Bean, spring eager initialization of Bean, Spring Lazy initialization of Bean, Lifecycle of Bean, postconstruct annotation, predestroy annotation, spring boot tutorial, spring boot, springboot, spring boot playlist, spring boot course
Id: Wd15hxveyME
Channel Id: undefined
Length: 33min 48sec (2028 seconds)
Published: Thu Apr 11 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.