Spring Boot basic annotations

 

Spring Boot Interview Preparation - Level 002


Explain the following Spring Boot annotations

  1. @EnableAutoConfiguration

  2. @SpringBootApplication

  3. @RequestMapping

  4. @GetMapping

  5. @PostMapping

  6. @DeleteMapping

  7. @PatchMapping

  8. @RequestBody

  9. @ResponseBody

  10. @PathVariable

  11. @RequestParam

  12. @RequestHeader

  13. @RestController

  14. @RequestAttribute

  15. @Autowired

  16. @Component

  17. @ComponentScan

  18. @Bean

  19. @Controller

  20. @Entity

  21. Difference between @RequestParam and @PathVariable

  22. Difference among @Component, @Service, @Repository and @Controller

  23. Difference between @Primary and @Qualifier


@EnableAutoConfiguration

Enables the Spring Boot Auto Configuration mechanism

 

@SpringBootApplication

A single annotation @SpringBootApplication is used to enable the following annotations

  • @EnableAutoConfiguration : Enables Spring Boot Auto Configuration mechanism

  • @ComponentScan : Scans the package where the application is located

  • @Configuration : Allows us to register extra beans in the context or import additional configuration classes


@RequestMapping

=> Used to map the web requests

=> It has many optional elements like consumer, header, method, name, params, path, produces and value.

=> We use it with the class as well as the method


@Controller

public class PoliciesController

{

    @RequestMapping(“InsuranceType/getPolicies”)

    public String getAllPolicies(Model model)

    {

        //application code

        return “PoliciesList”

    }

}


@GetMapping

=> Maps HTTP GET requests on the specific handler method

=> Equivalent to @RequestMapping(method=RequestMethod.GET)


@PostMapping

=> Maps HTTP POST requests on the specific handler method

=> Equivalent to @RequestMapping(method=RequestMethod.POST)


@DeleteMapping

=> Maps HTTP DELETE requests on the specific handler method

=> Equivalent to @RequestMapping(method=RequestMethod.DELETE)


@PatchMapping

=> Maps HTTP PATCH requests on the specific handler method

=> Equivalent to @RequestMapping(method=RequestMethod.PATCH)

 

@RequestBody

=> When we annotate a method parameter with @RequestBody, the Spring Framework binds the incoming HTTP request body to that parameter

=> We use this annotation as the method parameter

 

@ResponseBody

=> Binds method return value to the response body

=> We use this annotation with the method as well as class

=>  Converts the return object into JSON and XML format


@PathVariable

=> Used to extract values from the URI

=> It is most suitable for RESTFUL web service where the URL contains a path variable

=> We can define multiple @PathVariable in a method

It has the following optional elements

name : name of the path variable

required : tells whether the path variable is required

value : alias for name


Example :

Method :

@RestController

public class MyController{

@RequestMapping(path=”/{name}/{age}”)

public String getMessage(@PathVariable (“name”) String name,

@PathVariable(“age”) String age){

return String.format(“%s is %s years old”, name, age);

}

}


URL that we hit in the browser : localhost:8080/Ajith/20

Output : Ajith is 20 years old



@RequestParam

=> Used to extract the query parameters from the URL

=> It is most suitable for web applications

=> It can specify default values if the query parameter is not present in the URL

It has the following optional elements

defaultValue : used as a fallback when the request parameter is not provided or has an empty value

name : name of the request parameter

required : tells whether the parameter is required

value : alias for name

 

Example :

Method :

@RestController

public class MyController{

@RequestMapping(path=”/message”, produces=mediaType.TEXT_PLAIN_VALUE)

public String processForm(@RequestParam (defaultValue=”Guest”) String name,

@RequestParam(required=false) String adult){

var greet = “on”.equals(adult) ? “Good morning” : “Hi”;

return String.format(“%s %s!”, greet, name);

}

}


In HTML form, we submit the name and details and then it gets processed and returns the output page


<form action=”message”>

<div>

<label>Name : </label>

<input type=”text” name =”name”>

</div>

<div>

<label><input type “checkbox” name=”adult”>Adult</label>

</div>

<button type=”submit”> Submit</button>

</form>

 


@RequestHeader

=> Binds request header values to method parameters

Example :

Method :

@RestController

public class MyController{



//This determines the header User-Agent only

@GetMapping(value=”/agent”)

@ResponseStatus(value=HttpsStatus.OK)

public void client(@RequestHeader(value=”User-Agent”) String userAgent){

logger.info(“User agent is : {}”, userAgent);

}

//This finds out all the headers

@GetMapping(value=”/allHeaders”)

@ResponseStatus(value=HttpsStatus.OK)

public void allHeaders(@RequestHeader Map<String, String> headers){

logger.info(“All headers : {}”, headers);

}



}


Output for first mapping :

User Agent is curl/7.1.0

Output for second mapping :

All headers {Accept=*/*, User-Agent=curl/7.1.0, Host=localhost:8080}


@RestController

=> Used at class level

=> It can be considered as a combination of @Controller and @ResponseBody annotations

=> It eliminates the need of annotating each method with @ResponseBody

 

@RequestAttribute

=> Using this annotation, we can able to access pre-existing request attributes on the server side.


Difference between @RequestParam and @RequestAttribute

=> @RequestParam is used to bind parameter values from query string, ex : https://funkynshot.blogspot.com?myParam=3. Here, myParam=3 can populate @RequestParam parameters

=> @RequestAttribute is used to access objects which have been populated on the server side but during the same HTTP request.

 

@Autowired

=> Autowiring is used to create relationship between two objects in the spring container

=> If we declare @Component on the top of the class, it will create object in the spring container. Like that, Spring container can contain many spring bean objects.

=> We can use annotation @Autowire to autowire two beans


For Example,

Usually, Controller class will have handler method.

Service class will have business logic.

Model classes and DAO classes are for implementing Persistence logic.


Now, Controller class handler method needs to call the Service class method.
For that, Instead of creating new object for the Service class, we can use the annotation @Autowired to get the instance of the Service class

 
For more understanding :

 

(YouTube video credits to B2 Tech (https://www.youtube.com/@B2Tech))

 

@Component

=> @Component allows Spring to automatically detect our custom beans

=> Spring scans our application for the classes annotated with @Component, instantiate them and inject them wherever needed

 

@ComponentScan

=> It scans class path for classes and dependencies So that, the classes annotated with @Component will be auto discovered and registered as bean in the spring application context

=> Spring uses @ComponentScan to gather all the components into its application context

=> If we are creating Spring Boot application we must use the annotation @SpringBootApplication which includes the annotation @ComponentScan

=> As long as @SpringBootApplication class is root of our project, it will scan every @Component classes we define by default

=> If @SpringBootApplication class cannot be root then we must configure @ComponentScan explicitly. It will look in whatever package we specify.


@Bean

=> Spring uses the annotation @Bean to gather all the beans at run time

=> Its not a class level annotation

=> If we annotate a method with @Bean So that, spring can store the method’s result as a spring bean


@Controller

=> The annotation @Controller is a class level annotation

=> It is a specialization of @Component

=> It marks a class as a web request handler

=> By default, it returns a String that indicates which route to redirect.

=> It is mostly used with the annotation @RequestMapping

 

Example :

@Controller

@RequestMapping(“quotes”)

public class InsuranceController{

@RequestMapping(value=”/{insuredName}”, method = RequestMethod.GET)

public Quote getQuotesIdByInsuredName(){

return quotesId;

}

}


@Entity

=> @Entity annotation specifies that the class is the Entity of the database table

=> @Table annotation specifies the name of the database table to be used for mapping

=> @Id annotation specifies the primary key of the entity

=> @GeneratedValue specifies the generation strategy 

 

@Difference between @PathVariable and @RequestParam

=> Both @PathVariable and @RequestParam use the values from the URL

 

@PathVariable

=> Uses the url where we have path variables like this : localhost:8080/insured/Ajith/20

Example :

Method :

@RestController

public class MyController{

@RequestMapping(path=”/insured/{name}/{age}”)

public String getMessage(@PathVariable (“name”) String name,

@PathVariable(“age”) String age){

return String.format(“%s is %s years old”, name, age);

}

}


URL that we hit in the browser : localhost:8080/Ajith/20

Output : Ajith is 20 years old



@RequestParam

=> Uses the url where we have  query parameters like this : localhost:8080/insured?name=Ajith&age=20

Example :

Method :

@RequestMapping(path=”/insured/”)

public String getMessage(@RequestParam(“name” String insuredName,

@RequestParam String age){

return String.format(“%s is %s years old”, insuredName, age);

}

 
For more understanding,

Refer https://www.youtube.com/watch?v=OROTCvW1lZE (Credits to Infybuzz)


Difference  among @Component, @Service, @Repository, @Controller

=> @Component is a generic stereotype for any Spring-managed component.

=> @Controller, @Service and @Repository are specializations of @Component for more specific use cases

=> Similarity among all these four annotations is that, Spring will do auto-scan for the classes annotated with these annotations for registering and maintaining the beans in application context

=> @Controller :

    The classes annotated with @Controller act as dispatcher servlet so that Spring can identify the classes annotated with @Controller and maps the requests. That’s how it differs from other 3 annotations.

    Stereo type for Presentation Layer

=> @Service :

    We are using this annotation to indicate that the class is doing business logics. For now, no functionality difference between @Service and @Component.

    But its recommended to use @Service annotation for Service classes because, Spring may add some specific functionality in future.

    Stereo type for Service Layer.

=> @Repository :

    Classes annotated with @Repository used for performing database persistance logics.

    Special functionality of this annotation is that it can through exceptions related to database/persistence

    Stereo type for persistence layer

 
Where we use @Component?

If a class is apart from dispatcher servelet, business logics, persistence logics and just need to register bean in application context, then we can use the annotation @Component for it.


For more understanding,

Refer https://www.youtube.com/watch?v=zJBfC96EYd8 (Credits to TechTalkDebu)

(Credits to TechTalkDebu (https://www.youtube.com/@TechTalkDebu))

 

Difference between @Primary and @Qualifier

=> @Primary indicates that the bean is primary bean and it should be given precedence when more than one bean meets the requirement for autowiring.

=> @Qualifier directly indicates the bean name and tells Spring which bean should be autowired

=> @Qualifier has bigger priority than @Primary because, @Primary means default implementation whereas, @Qualifier is specific implementation

For more understanding,

Refer https://www.youtube.com/watch?v=2YC5pIXR7e4 (Credits to Simple Programming)

(Credits to Simple Programming (https://www.youtube.com/@simpleprogramming1612))