Interview QA | 40+ Spring & Spring Boot Annotations Everyone Should Know | JavaTechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to java techy nowadays everyone using spring or spring boot framework to develop their web application right in fact i extensively worked on these two framework while working i found there are tons of annotation given by these frameworks and sometimes we are using those annotations without knowing its functionality isn't it which is not a good practice so to make you understand what are those annotations and at what time we can use those annotations i prepared one cheat sheet with 50 plus annotations okay so we'll go through each and every annotations with example so that you don't need to buy it these annotations and its uses okay so without any further delay let's get started [Music] so i created one small springboard application to demonstrate all its useful annotations with since we started with spring boot application and we know that spring boot app starts with main method so let's begin with the main spring boot annotation that is at the right spring boot application okay so this address spring boot application annotation is a convenience annotation that combines other annotations like are there at enable auto configuration at the rate component scan and at the rate configuration now if you go to the source code of other springboard application you can find here it is just a alias for address enable auto configuration at the right component scan and other rate configuration fine now let's understand role of each annotation so this addret enable auto configuration annotations this automatically configure the spring application based on the jar dependency that we have added in our palm.xml for example if the h2database jar is present in the class path and we have not configured any bins related to the database manually then spring boot auto configuration feature automatically configure it in our project okay now the next one are the rate component scan this is just a simple annotation where it will just scan your bin so that it can visible to the ioc container okay let's say you define a different package structure or you just want to load specific package and class to ios container then you can use other rate component scan and you can provide the base packages or base classes okay now the next are the rate configuration we use this annotation for java based configuration where we can define the bin definitions inside this class so that spring ioc can load it okay so these are the three annotations spring developer or spring boot developer combine these three annotation to a single annotation that is the root one at the red spring boot application okay fine now let's discuss about stereotype annotations spring framework provide us some special annotations like at the rate component or threat service or threat rest controller and other repository these are called stereotype annotations basically these annotations are used to create spring bin automatically in the application context if you annotate any of this annotation on top of your spring bin then spring will scan that bin and manage its life cycle begin from object creation to object destroy okay so this other rate component annotation is the main or best stereotype annotation you can say and other three are just derived from the earth rate component annotation okay now if i can show that in the source code let me go to any of the class repository so you can see this is what the component this is the root annotation okay now if i will go back and if i'll type all the annotation here to just show you that others are just derived from address component so i'll just type service then i'll just type other repository then add the rate controller if i will open the service this is what the derived from the component class and similarly address repo this is what also derived from the component class and are the rate controller this is also derived from the component class right so let me remove all this is not the recommended way to write these annotations i'll just remove everything okay so now you might have a question why there are four annotations as you know other component is the parent annotations and everywhere we can use it right that's absolutely correct we can use it but the main purpose of other annotation will tell the role of that classes okay like if you annotate at the right controller someone easily identified that okay this is what the web layer where i can expose my rest api so just go to the controller class so i defined your other rest controller so that easily someone can identify this is what the class where i can expose my rest endpoint correct now similarly if you will go to the service class service implant by seeing this other service annotation someone can easily identify that okay this is what the class where i need to write my business logic similarly if you will go to the repository class by seeing this annotation someone can easily identify this is where i need to write the database logic okay that is why there is three different annotation to just define a role of that classes okay and also it's a good practice to specify meaningful annotations in each layer okay hope you get the clear picture about stereotype annotations so this is one of the interview question guys now let's discuss about spring core annotations so there is list of sprinkler annotations earth rate configuration bin auto ad qualifier lazy value property source configuration properties profile and scope i'll i'll explain each and every annotations with example okay so let's begin with the other right configuration and at the red bin usually these two annotation used when you want to use java based configuration when i say java based config it means we don't want to handle the spring bin life cycle either using annotations or xml so when you write address configuration it indicates that the class can be used by spring ioc container as a source of bain definition okay let me write the code to explain about this annotation so let me write a some class called bean config or something like that okay and i when i annotated your other configuration now spring ioc will expect from this class to define couple of bean annotation i mean just define couple of bean which will return the object for example let me create a bin let's say test bin or something like that okay in this test bin i will write a method public some some random method okay public board method then i'll just print something is out just print something test bin method logic executed something fine now how can i define this as a spring bin there is two way i can use the xml otherwise i can simply annotate your other rate component right but i don't want to do that i just want to define this bean definition inside my config class how i can define it simply just create a object of it okay just test bin then just return some object return new test bin object fine and just annotated here at the red bean annotation so here when you start your application spring ioc will search annotation with other configuration then you will search for a annotation address bin inside these address configuration classes once you find other bin then immediately spring ioc will create object of it and will maintain its lifecycle by himself okay now to show you that let me inject this bin somewhere so that i can show you that okay so in controller i have few end point i will just use here so i need to inject that bin right so that i can access it private test bin test bin i can inject using arthritis then i can simply call here ah test bin dot method fine let me run this application when i access this api it should call the method of this test bin class so i will just run it it will take few seconds so you can see here it started on port 8080 now let me clear this console if i'll go to the browser if i'll type localhost 8080 students then get all the students i got all the four object which i added in my h2 dv and i just want to verify the method call right test bin method logic executed now we didn't create the object of test bin it's just created by spring ioc by reading this bin config class so if you remember we usually create the kafka configuration or raise template configuration inside or that configuration class right we are doing something like this public create the object of race template then get the template object just return it right new race template this is how we usually do right and we are just annotating here at the red b and then wherever you want to use this rest template we are just injecting it using auto weight that's it right so this is how we can define a bin inside a configuration class so i'll just remove it because we are not using any rest template here now now let's move to the next one that is address auto add so if i will go to the any class let me go to the controller class so if you observe in this controller i just want to use the object of the student service class okay so if you observe this student service is a interface and it's having the implementation student service impl so this object i want to use in my controller class that is where i just tell to the spring boot i just inject using arthrit auto add you create object of this class and give it to me so that i can use it okay now to show you what i will do i will just remove this auto add annotation okay so if i will remove this spring will not able to create the object of it because we are not creating object manually right so let me run this class i will just rerun it definitely you will get the exception here okay so that is the reason we need auto add but i just want to show you that exception so server started here now i'll just access the endpoint i'm getting 500 internal server error because i believe i will get the null printer exception yeah i am getting the null pointer exception in line number 43 okay because of this student service dot get student since we are not creating object of it i will get null object and null dot get students will throw me the null pointer exception okay so that is the reason you need to tell to the spring boot or string framework just inject this bin i used arthrit autoid annotation you just inject this object in my class wherever i want to use it that's it now if you observe there is a challenge so in student controller i just injected a interface student service right and if you observe there is one implementation class only one implementation class now let's say in future i just want to define another v2 version of this implementation class let's say student service impl b2 of it okay this is the version 2 of the service impl i'll just implement it from student service and i will just override the methods i will not give any logic for now i just want to show you the use case so just annotated here at the red service fine now for the student service i have two implementation so if i click here there is two implementation right student service impl which is the v1 version and student service b2 version with some enhancement now if i run this application it should work right let me run this then we'll find out what is the problem here okay first let me run it let's clear all so you can see here you're getting some exception here so if you read it carefully filled student service in this controller class required a single bin but two are found this controller class is expecting a single bin but there is two bin one is the service ample and another is the service sample b2 right so you can see here these are the two classes now if you see the action here consider making one of the bin as primary updating the consume what is this consumer to accept multiple bins or using other rate qualifier to identify that bin that should be consumed now if you see this action it already provided you the solution you need to tell to the springboard i have an interface and that interface having the having the two implementation now you need to tell the which exact bin you want to load here whether student service impl or student service impel b2 you need to tell to that spring boot how you can tell it you can tell using annotation or direct qualifier here you can tell the springboard please load the bin the name which i am giving okay so for now if i will give this one student service impl let me go to the controller you just need to provide the earliest name of it okay i am telling to the springboard for this particular interface there is two implementation but you ignore whatever i am giving you just load this whatever the bin name i am specifying you just load that particular bin object okay now if i will run this there will be no exception you can able to access your api so let's wait it to complete so it started now if i will start the application or if i will just hit the end point i will get the response here right so now that is what you need to use the qualifier now if you'll see the next annotation is at the rate primary right i missed it i believe let me add it that is also one important annotation at the red primary now if you observe in the core for this particular student service there are two qualified bin student service impl and student service imple2 if you don't want to use qualifier and always you want to give the priority to a single bin either student service impl or student service impl b2 whatever the scenario i just want to load this particular bin i don't know anything then you can simply use the other rate primary annotation so just go to that particular class which been you want to give a priority just annotated here at red primary here okay so i will just remove this from the qualifier because i don't want to use it i just want to give a priority to a specific bin that is where i just added primary here okay now if i will run our application always this particular student service inpl b2 will be injected in my controller so let's test it so if you observe everywhere where we are returning the null right so there is no logic will be written from the code so we'll just verify it yeah now if i will access it i won't get any response see here now if you will go and check there is no error it means this is just injecting the student service ampl b2 because the return type is null and we are not able to see anything so for now i will just make the primary as student service impl not b2 so i will just give here fine now okay let me do command j fine now just run it so usually these are the right primary annotation the best use case of it when you have multiple data source or database configuration been in your application you can give a primary to a specific connection either in mysql or mongodb you can define the database connection and you can give a primary annotation so already i explained are there primary annotations with example you can check out my spring boot with multiple data source video okay you can find the exact use case of further at primary so i believe it started yeah now if i'll access it i will get the response because the service impl is injected to my controller fine now let's move to the next one that is at the red lazy annotation as you know by default spring bin are eager loading right i mean if you define bean in your application then spring ios will by default create its object however it does not matter whether you are using that bean or not which really increase the heap right now how we can avoid that so there you can use other lazy annotations we can tell the spring or springboard hey just create or load the bin on demand only otherwise you keep quiet don't do anything okay so let me show you an example of lazy loading so i will just minimize this i will create a bin here i will just create two bin to show you the eager loading and leg loading behavior of spring so i will just create a java class ledge loading bin okay then i'll create another class new java class limit eager loading bin fine so this is where the eager loading i will just define a constructor to just print that the object is created yes out i'll just print ego loading bin or object created okay object created same statement i will just add in my lazy loading so since this is the bin either i can define using xml or annotation so here i will use the component annotation okay now go to the lazy loading bin i will also define the constructor here and i will add a statement here ledger loading bin object created okay i will also define this as a other component now if i will define other component then by default this object will be created okay so what i'll do let's define then we'll differentiate it so i'll just define now since i define component for lazy loading and equal loading both object will be created by spring ioc right because we annotated here now this i just want to load it lately whenever i want it i will tell to the spring boot to load this bin so i just define it at the ledge now simply let me rerun this application will see which object spring created so it will take few seconds yeah now if you observe the output here it's just created the object of eagle loading object okay which is the eagle loading bin now if you observe here there is two beam you go loading and lazy loading in eager loading we just define other component so spring will create its object see here eager loading bin i am not using it anywhere in my other package right but still spring boot is creating its object it means this spring boot is eager loading okay and if you don't want to achieve that eagle loading you want to load your bin whenever you need it then you can define other lazy now what i'll do i will just inject this bin or i'll just use this bin then only spring will create object of it okay so to prove that what i will do i will just go to my controller and i will just define this bin private what is that lazy loading bin lazy loading bin i'll just define address auto add then i'll just call the i'll not call anything i'm just injected it right that's enough spring will understand okay somewhere these guys want to use that particular bin so i need to load it okay so i'll just read on this so here if you can see even loading been object created lazy loading been object created once we use this legion loading bin then only spring created its object because of other lazy annotation right i believe this lazy loading or threat lazy concept is clear for you now let's move into the next one that is address value annotation okay so whenever you want to load some metadata from the properties file then you can use other rate value annotation for example let me define some key value in our application.properties file let me go inside other resource class i will go to the application.properties file let's think that i want to load this key value related to the mail okay i just want to build some api will trigger the email using java mail sender so for that i just need this three field from host and port so i just define these three in my properties file as a key and value and i want to load these three properties value how i can do that i can do that using ah other rate value annotation so for example i will just go to this controller class i will write everything here only okay so that i can show you so here i just want to get those three value private string host then what is that let me cross verify once again from host and port right so i'll just go to the controller class then i'll just define here private string from then private string i'll give portrait so using address value i can get that particular value from the metadata or application.file now how i can load that from i just need to define the key here ok using other red value annotation i will tell to the springboard go and check in my application.properties file and load this key what is the key this is what the key to load if you will specify this key spring will load the value for you go to the controller just define that key fine similarly i'll just define for other two field this is for host you need to give the valid key whatever you mention here there is no spelling mistake okay then this is the port now i just want to print it somewhere so i can do something like i can print it here only okay sys out then i can print something like from then i can print here let me add a space host then i can define port here okay so i will just add some random string here to understand male props load using at the red value fine so i'll just restart the application now application started in port 8080 and we just defined this inside all endpoint right let me call that before that let me clear the console first i'll just hit the endpoint so if you observe here it's getting printed right mail props load using other value annotation this is from this is host and this is the port that is what we defined here right that's fine now if you observe we didn't give the name of our properties file to the springboard right now if you go to the student controller we just tell to load this particular key from the properties file but which properties file you didn't specify anywhere because currently you are loading it from application.properties file that will be automatically load by spring boot but if you will define your custom property something like let me define a properties let us say custom [Music] properties then spring boot unload this particular property so let us say i will just name it key one and then this is the value but let's not do that let me give some message message so i'll just give loading from external props you can give any key value whatever the mail things mail from host port i can define here also okay but to show you that if you're not using the application.properties file how you can tell to the springboard that load these particular custom properties that is the reason i just added some dummy key and value so what i'll do in this student controller i'll just tell to the springboard load the properties file which i am giving so there is annotation called property source and here you can define the file name so i'll just define the file is there inside my class path the name of the file is custom dot properties okay and i will just load the field which is private string message and i'll just enter here at that value and i'll just give the symbol dollar then give the key name okay so if you check here the key name is message so you can rename it whatever the key you want you can give it for now i will keep it message only and i will just give it here now if i'll run this code okay i just need to print this somewhere right so i'll just print it here only s out new value what is that message fine now let me read on this so application started on port 8080 go to the browser just run it and if you'll go and check in the console you can see here right the new value loaded and also application.properties this is loaded by default and this is what we loaded externally by using address property source that's fine right now let's move to the next one that is earth rate configuration properties so this is very interesting annotation i'll tell you the exact use case of this address configuration properties let's say you have bunch of key and value in your application.properties file or your custom properties file okay so rather than load it one by one let's say you have data source properties where driver class name username password url like all the n number of field you have okay and you want to bind them a dto class or a single bin class and you want to map those key to that particular detail then how you can do that for now let's try this mail okay mail from mail host and mail port these are the three keys there i want to map this value to a single bin or dto class how i can do that let me create a detail i will just define here only guys i'll just create a class mail props or something like that fine and then i just need to define address configuration properties and inside that you need to provide prefix okay i'll tell you what is the prefix now if you will see in my application.properties file key is mail. from mail.hostml.port right now what is the unique word here that is the mail okay so i can consider that this as a prefix now if i'll do mail. from it should give me this mail.host it should give me this right so i can define the mail as a prefix here then simply i will define these three fields so i will just copy it from the controller i don't want to write it again these are the three field right i'll just copy it go to the mail props then i will just remove it because i don't want to load it manually i want to load it using the other configuration properties this is really interesting it can be i don't know i used it many times but once you invert with this other configuration properties once you understand it you definitely used it in your project whenever you are loading the external properties okay so since i added lombok i can use other data otherwise you can write at the right greater and setter to tell to the string that this is my bin i can annotate at the right component fine now with the prefix it will load from host and port now if i will go to my controller class and i will just remove these two then we'll just only print the mail props okay so i'll just inject that mail process first here private mail props mail props then i will just use other autoaid fine then i will just print it guys s out mail properties then i can print it since i added other data by default to string method will be available for now i'll just restart this yeah so it started now i will hit the end point this is what the only single endpoint i am doing modifying here guys okay so i just ran it now go to the console you can see here right all the key mapped to your dto class which is mail props fine now let's move into the next one that is at the red profile okay so this annotation is really very useful i believe everyone must use it in their project we usually use this annotation whenever we want to load some configuration specific to the environment let's take an example we are using database in our project right and each environment specific data source properties or connection database connection properties are different for development driver class name url username and password are different than other environment like stage or production right as a developer when i write and test my code i should use development environment specific database connection and when you want to debug some bug we need to use stage database connection right now how i can switch from one environment to another that is where at the rate profile annotation came to the picture now if you will see the code and if you will go to the resource folder i'll just show you here in the resource folder i have the file name application hyphen dev dot properties application hyphen test.properties and application iphone pro dot properties right so here i define three different properties specific to separate environment okay so this application hyphen dev dot properties here i can write all my development environment related configuration similarly in stage i can define all my stage environment related configuration it can be database configuration or configuration because things are varied from one environment to another environment right similarly this is for production now i am just debugging the code one of the bug i found and i just want to debug it in lower environment in stage environment then how i can tell to the springboard that there is three application dot properties specific to the environment they have stage and prod just load the stage for me so that i can continue my testing right that is where we can use other rate profile annotation now if you will go to the config package so i created one class called dv config okay here i am just loading the driver class name url username and password and and then i am simply printing it i am nothing i am not doing anything here okay so i will i will just load the key from the corresponding file from that specific environment based on the profile so if you observe here i just specify the profile stage now stage means it will go to this application iphone stage dot properties and it will load this key okay so let me show you that i will just run this or apart from that if you go to the application.properties file also you need to specify who is your active profile that environment you need to specify here okay now if i will quickly run this you can see in the console that it will print the stage related database properties okay we'll see that so here if you can see the console we are just loading the stage related database connection here right stage dv driver uh db url the username and dv encrypted password so that is what we just specify here right that is what the value we are getting here now let's say there is some issue on the production i just want to switch to the production environment so how i can do that simply go to the dv config and just change it to the prod okay also go to the application.properties file that you are the main file and just change this spring profile active to prod now let me rerun our application now you can see here instead of stage it should print production related uh data source properties okay so let us wait it to complete so if you can see here the prod db driver class brought the url for the username and password it loaded based on the active profile which we set in our application.properties file and also based on other profile annotation so this is what one useful example of using spring profile you can use using this annotation or also you can go with the xml approach okay now let's move to the next one that is address scope this is the last annotation of spring core related annotations which we defined here now let us understand this earth scope okay this particular annotation indicates scope of win such as singleton prototype or session or request okay so how we can use this other scope annotation just go to a bin wherever you want to define the scope of that bin so if you define a bin scope as a single term then it will just create a single object for a context okay for application context if you define a bin scope as a prototype based on the number of requests or based on the num how many time you use that particular instance it will create a different different object to prove that what i'll do i'll just go to the controller and in the controller what will just define the scope here okay so scope i'll just specify the scope name as singleton then what i'll do i'll just create a constructor of it so that i can print that whether object is getting created or not so just create a empty constructor i'll just add this then i'll just add a sapling statement okay controller object created fine now i'll just since we define the bin scope as a single turn it will only create one object as many as request will send it does not matter it will create only one object okay so let me start it so if you can see the output here controller object created here okay i will just clear this console and i will just try to access controller many times fine four five many times i hit the same end point now if you will see there is no further statement about controller object created because the object create once then it stored in application context that is what the spring reused it now if i will define the scope as a prototype then see what will be the difference between this singleton and prototype i'll just define proto type i'll just restart my application now if you observe here there is no object created yet let me hit the end point one i will hit multiple times two three four five six seven if you'll go and see as many times i hit the request controller object getting created here okay that is what the difference between prototype scope and singleton scope similarly you can give a try the request and session okay so i believe we almost covered all the annotation about spring core hope this spring core annotations is clear for you now let's move to the next set of annotations about rest api related annotations okay we'll go through each and every annotations and we'll try to understand it when we say rest api fast annotation com in mind that is addressed rest controller with these annotations we defined that this is the class where we exposed our rest endpoint and this is one of the stereotype annotations which we already discussed if you see in my controller class i'll just stop this server if you'll see this controller class this is where we annotate at the rate rest controller and here i define three endpoint one to save the student object one to get the student object based on the id and another fetch all the student object okay these are the three rest end point i'm exposing from my controller class and to tell to or to specify the role of this class i define this is what my controller with annotation address rest controller right now the next annotation is at the rate request mapping this is quite old annotations which introduced to define http methods i mean using this annotations you can define what http method you want to expose your endpoints okay for example let's say uh here i just want to or in this particular line i just want to change something like i want to use request mapping okay i don't want to use this at the right post mapping i will come to this point later so i just want to use the old annotation which is request mapping here i just need i just need to define the which http method i want to use so i can define method then i can define uh request that there is a num which i can use request method post right because i want to save something then you can define the url but first let me define the url let's say i just want to use the url as class save and this is what my method type then you can also define the consumes media type so i'll just give application slash json fine similarly you can also define the produces media type i can give application slash json so you can write like this but usually in latest spring version we are not using this annotation because string developer provides separate annotation for each http method like gate mapping post mapping boot mapping and delete mapping okay so you can see here get mapping post put and delete mapping that is where we are just using the other post mapping you don't need to define those method type and the consumes and produces okay everything will be take care by the annotation and if you observe this post mapping also inherited from request mapping similarly if you check this gate mapping also inherited from request mapping all these four annotation post get put delete inherited from request mapping annotation okay now why there are four annotations so each annotations define specific role here if you want to fetch something or if you want to retrieve something then you can use other gate mapping if you want to save some information to the database or if you want to perform some create operation you can use other post mapping if you want to perform some update operation then you can use other red boot mapping similarly if you want to delete something then you can use other delete mapping okay so if you'll see the code i just want to save a student object to database that is where i just use post mapping and whenever i just want to fetch object from the service or dv i just use get mapping similarly you can write boot mapping or delete mapping you can check out my spring boot crowd example video okay you'll find all the four annotations and their uses that's fine now let's move to the next annotation that is earth rate request body now if you observe in my code i just added other rate request body annotation in post method argument right here i want to perform post operation i mean i want to save the student object to the database okay so that is where the code i wrote in this particular endpoint now how can i access this endpoint i just need to define the url and then i just need to pass this student json as a request body from the postman something like this okay id name rule number and department so if you observe in the student class these are the field id name rule number and department that is the field i am just giving here right in the postman now the question here so when i pass a json object from the postman then how does it map to the student object which is there in my method argument and then that student object will going to the save in the dv right so let me hit the end point okay okay i just i just need to start the server okay so better let me debug it so that i can show you let me start it in the debug mode so server started now once i pass this json object and once i send the request request will come to this controller now if you observe the whatever the json i passed here that mapped to this particular student object and you can see the value of student here right id name rule number department the json getting deserialized to the student object isn't it so that is where this request body annotation help us it will automatically this realize the body of http request into the dto or model whatever you defined here okay that is the reason we are using request body annotation so i'll just pass this fine now let's move to the next one that is other path variable and request form so this request body annotation we use to pass the payload but there may be a possible scenario that you need to pass the input as part of request url itself okay so that is the case you can use address path variable so i just want to pass the input as part of request url now if you observe i just want to get the student based on the id and this id i will pass as part of request url right now what is the url students then i just want to access this particular endpoint give the id of student and face the student object from the db now if i'll go to the postman if i'll type students then i will just give the id this is what we just added right i will just give this id now if you observe here i am giving this input 1 0 1 9 as a input parameter to the my request url right if and i will just remove this because this is the gate api right now hit the request okay let me mute the breakpoint go to the postman you can see the response here right so this is how you can use the other path variable and if you want to pass input as part of request url also you can use other rate request param rather than using this path variable so you can use annotation call request param and you can remove this you can give some id here id by request or something some random id or some random url and you can provide the parameter which you want to pass as part of request okay you can give something like that i am not going to write it but i will just show you you can go to the chrome and you can add this rather than giving the path variable what is the url you specify id by request you can specify id by request then what field you want to pass that is id and you can pass the input here let's say 109 and then you can hit the end point you will get the result from the dv okay so i will just revert these changes okay let me revert it fine now you might have a question why there is two annotations to pass the input as part of request url right you can give using other request param you can give using a path variable what is the reason behind it i'll tell you if you will use other path variable and then you are not giving the input then you will get four not four so if you are using path variable you are force or you are mandate to pass the input otherwise you will get the four not four but in case of request param it is optional if you will not give the input there is no harm you won't get any exception for example let's say i'll just show you here so this is what the end point right if i will give this i will get the result since this is the path variable code i will not give anything okay i'll just get the 4.4 but if you use the request form there is no exception that is request param won't force you to pass the input as part of your request url so it depends on your business what need to use whether the field is mandatory or optional based on that you need to decide whether need to use path variable or request param okay now let's move to the next one that is earth rate controller advice and other exception handler okay usually these two annotations used to handle exception in your application now if i will show you in the code let me go to the yeah this method get student so i am giving the id based on that id i will face the student object if it is present i will return it if that that is not present in the service then i am just throwing the student not found exception so i just created this class today not found exception and i am just throwing that exception fine now here when your controller throws this particular exception then immediately spring or spring boot will search a class which is annotated with other other rest controller advice or at the rate controller advice okay once he found a class immediately he'll delegate request to that corresponding class and inside that class it will just find the matched annotation or matched exception okay so if you observe in this controller we are throwing student not found exception and then in rest controller advice we have already mapped the student what is the student not found exception right if you will go and check here already we found the matched exception which we are throwing from our controller and there we annotate other exception handler fine now in this class simply we are telling to the spring this is the method okay i will build my custom error message and i will return it back to the end user okay so that is where the other rest controller advice and other exception handler annotation is required to handle the exception in your rest api okay so if you want i can debug it and i can throw okay let me add a breakpoint so that i can show you let's go to the controller class fine just add a breakpoint i'll just remove other breakpoints fine now since we already started on debug mode i can directly test it out go to the postman i'll give some id which is not there in my dv i'll give some random id okay and i will send the request request came to here then it will just go to the student service and i will just pass it now if you see the student is empty right so i am checking student is present if it is not then throw this exception so once your controller throws the exception immediately request will delegate to this rest controller advice class okay so this is what the advice class so the breakpoint will come to here okay why it's not again i'm not sure let me build it i believe let's see i'll just add it i'll just resume it you can see here request immediately delegate to this here because it found the matched exception that is why we annotated early exception handler fine now request come here it will just build the app error object i just created this uh particular dtu class to define the error code message and http status fine it will just build that and simply it will just return it now if you go and check in your postman we are getting error code some random uuid number message student not found with this id and the http status which i am hardcoding here that is what i am getting here right so this is where these two annotation helps to handle the exception in your restful web services okay so i hope this rest api related annotation is clear for you now let's move to the next one that is string data jpe related annotations okay so if you observe here there are few annotation at the rate entity at the table or the rate column or the transactional then also there is some association mapping related annotations between entity to entity one to one one to many many to one and many too many okay so let's begin with this four annotation entity table and column so if we'll go to the any entity in this jpa implementation or it's specific to the hibernate also if you'll go to the entity i created already one student entity that is what we are just storing to the dv and we are retrieving it right now if i will go inside this entity i have the field called id name rule number and department so i just defined this other entity by annotating this i am telling to the jpa or hibernate this is what the object i want to perform db operation okay so that is where you need to define the address entity annotation and also if you observe i just annotate at the red table here to define that to create a table with the name which i am giving you can define this particular annotation if you will not define this other table annotation then hibernate or jpa will create a table based on your entity class name with student okay so it depends on your use case if you want to customize your table name you can define other table annotation then these two are the mandatory annotation entity and table and then next i define the field id name rule number and dependent right you must need to define one primary key with the annotation at the rate id and again this column annotation is optional if you want to create your custom column name if you will not specify first of all you will not specify this column then the column will be created in dvr with this variable name id name roll number and department but if you want to customize then you can define your own name what you want to create for column okay apart from that if you want to also create id auto generated then you can use other red generated value ok generated value if you want to define generated type or generator type in hibernate there is couple of generator you can use it so let me see if i can see the option ctrl space ok you can define couple of type here guys let me see if i can see the enums fine i will list out all the generator type but you can define the custom generator or default generator of fiber net using this annotation fine now let's move to the next one that is address transactional so if you have any association mapping in your application and if you want to roll back the transaction if something going wrong let's say you have user and payment entity if payment is getting failed you don't want to save user information in the db you want to roll back all the transaction i mean you just don't want to store the payment as well as the user if there is a failure then in that case you can use other transactional annotation so already i uploaded video how to use transaction string transaction you can check out that it will be available on my springboot playlist but i will just show you the annotation here okay so just go to the any class service i don't have that scenario with me now but i will just show you with the annotation okay so let's say for this art student i just want to implement other transactional so you can use transactional annotation and there you can define isolation and also you can define the propagation okay so isolation you can define let me check the enum type isolation read committed okay then you can define the propagation require new or something like that okay let me check yeah require new or you can define the required required yeah you can define this fine with this annotation you can tell the spring or spring boot framework that this is the method i just want to implement the transaction if something going wrong don't save any information to the database just roll back it okay so if you will write this annotation manually you no need to write tx commit or tx roll back okay spring will take care everything so for now we don't have any transactional scenario i'll just remove it now let's move to the next one that is entity class relationships so it depends on your use case which association mapping you need to choose for example let us say i have a student here right a student can apply for multiple course right so then i can define a mapping here i can do something like course then i just need to define a class called course let me see i have the option create class course file this will also one entity right i can just add a annotation let's say these are the annotation and not write the code i will just show you the annotation type okay then you you must need to define a field private int id then private course name okay okay string course name then you must need to define this other right id guys fine now i am just telling here a single student can apply many courses okay that is where the scenario will be student one can multiple course or many course so the annotation should be one to many fine and here you just need to define who who will be your target entity uh what is that target entity right target entity which is nothing course dot class right dot class and you can define the what is that face type face mode eager or legi similarly cascade and also you need to define the join columns fine and you just need to define the name of it you can give something like student foreign key this is what the example of one to many similarly you just want to reverse it right many to one what you can do rather than just inject here just go to the course and just inject the student here private student student and here you can do the reverse one minute one many courses can be applied by a single student so you can use this again you can do the target entity phase cascade everything you can define here okay if a single entity let's say student is just mapped to a single entity then you can use one to one there is no possibility that a student can have multiple address right so in that case student with address you can do one to one so you need to find out a scenario that what exact association mapping fit for that use case based on that you can define the um these annotations okay so i believe this session is clear for you there are few more annotations which i supposed to cover but i will not cover in this today's tutorial we'll just continue a separate part for it okay so there are few annotations specific to security cross origin secured pre-authorized permit all then few annotation for caching then few annotation for aop aspect oriented programming aspect point code then after returning after throwing around v4 on spring cloud related annotations kafka related annotations we'll continue this in next part of our video okay so based on your response i will plan for the next tutorial thanks for watching this video guys that's all about this particular video guys thanks for watching this video meet you soon with a new concept
Info
Channel: Java Techie
Views: 160,955
Rating: undefined out of 5
Keywords: spring annotations, spring boot annotations, spring, spring boot, javatechie
Id: htyq-mER0AE
Channel Id: undefined
Length: 61min 58sec (3718 seconds)
Published: Sun Mar 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.