Spring Boot - Annotation Cheatsheet Pt. 1b

Written by sumithkpuri | Published 2023/01/05
Tech Story Tags: spring-boot | programming | cheatsheet | coding | software-development | software-engineering | software-architecture | programming-tips

TLDRThe more I learn, the more I realize how much I don't know,' said Albert Einstein. So, How much percentage (depth and extense) of Spring Boot annotations do you think you really know? This includes annotations in all it's glory and the power that they bring via all of it's 'options'via the TL;DR App

In continuation of the Part 01/a of this article, Let's continue on our journey of Spring Boot Annotations. So, How much percentage (depth and extense) of Spring Boot Annotations do you think you really know? This includes annotations in all it's glory and the power that they bring via all of it's 'options'.

I am sure whatever your answer be, I am sure you will appreciate this quote from Albert Einstein.

‘The more I learn, the more I realize how much I don't know.'


GitHub Repository

https://rebrand.ly/skp-sb-annot-git


[Spring- Stereotype]

@Service

Service Layer usually holds the core business logic of an application. In Spring, we denote the interface or class that holds the business logic with this annotation.

 package xyz.sumithpuri.spring.boot.annotation.service;  
   
 import java.util.HashSet;  
   
 import org.springframework.stereotype.Service;  
   
 import xyz.sumithpuri.spring.boot.annotation.model.Book;  
   
 /**  
  * @author Sumith Puri  
  *  
  */  
 @Service  
 public class BookServiceImpl implements BookService {  
   
      HashSet<Book> bookList = new HashSet<Book>();  
   
      @Override  
      public HashSet<Book> findAllBook() {  
           if (bookList.isEmpty())  
                return null;  
           else  
                return bookList;  
      }  
   
      @Override  
      public Book findBookByID(long id) {  
           Book book = bookList.stream().filter(b -> b.getId() == id).findAny().orElse(null);  
           return book;  
      }  
     ....  


@Controller
@RestController

@Controller is a specialized component that is primarily used in the web layer. It is typically used in combination with annotated handler methods based on the RequestMapping annotation. @RestController is annotated with @Controller and is used for web layer request handling.  Types that carry the @RestController annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

 import java.util.HashSet;  
   
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.web.bind.annotation.DeleteMapping;  
 import org.springframework.web.bind.annotation.GetMapping;  
 import org.springframework.web.bind.annotation.PathVariable;  
 import org.springframework.web.bind.annotation.PostMapping;  
 import org.springframework.web.bind.annotation.RequestBody;  
 import org.springframework.web.bind.annotation.RestController;  
   
 import xyz.sumithpuri.spring.boot.annotation.configuration.SBASampleConfigurationProperties;  
 import xyz.sumithpuri.spring.boot.annotation.model.Book;  
 import xyz.sumithpuri.spring.boot.annotation.service.BookServiceImpl;  
   
 /**  
  * @author Sumith Puri  
  *  
  */  
 @RestController  
 public class SBASampleController {  
   
      @Autowired  
      BookServiceImpl bookServiceImpl;  
   
      @Autowired  
      SBASampleConfigurationProperties sbasConfigProps;  
        
   
      @GetMapping("/findall")  
      public HashSet<Book> getAllBook() {  
           return bookServiceImpl.findAllBook();  
      }  
   
      @GetMapping("/findbyid/{id}")  
      public Book geBookById(@PathVariable long id) {  
           return bookServiceImpl.findBookByID(id);  
      }  
     ...  

**@Component

@Component is used to create any Spring managed component. It can be used as a Spring Bean. Any bean with @Bean that is created within a component will have a 'Prototype' scope, as opposed to a 'Singleton' scope of beans that is created within a @Configuration annotated class. @Repository and @Controller are all specialized components

 package xyz.sumithpuri.spring.boot.annotation.component;  
   
 import javax.annotation.PostConstruct;  
   
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.stereotype.Component;  
   
 import xyz.sumithpuri.spring.boot.annotation.service.SBASampleInterface;  
   
 /**  
  * @author sumith.puri  
  *  
  */  
 @Component  
 public class SpringBootAnnotationComponent {  
   
        
      @Autowired  
      private SBASampleInterface sbaSampleInterfaceImpl;  
        
      @PostConstruct  
      private void postConstruct() {  
           System.out.println("Testing @SpringBootApplication, @Component and @PostConstruct");  
      }  
   
 }  

**@Repository
**@Repository is a specialized @Component that is used to mark a class that provides persistence or storage operations. It will provide operations like create, update, retrieve, delete and search type of operations. It is mostly used in conjunction with RDBMS or any other Database


[Spring - REST/Web/MVC]@RequestMapping

This annotation is from MVC/Web that will associate a given URI with a method in the controller. It can be used in the following format.

 @RequestMapping(method = RequestMethod.PATCH)  


**@GetMapping
**This annotation is used to map a HTTP GET request to a specific handler method in the controller. It is equivalent to the following alternative.

 @RequestMapping(method = RequestMethod.GET) 

**@PostMapping
**This annotation is used to map a HTTP POST  request to a specific handler method in the controller. It is equivalent to the following alternative.

 @RequestMapping(method = RequestMethod.POST) 

@DeleteMapping

This annotation is used to map a HTTP DELETE request to a specific handler method in the controller. It is equivalent to the following alternative.

 @RequestMapping(method = RequestMethod.DELETE) 

@PutMapping

This annotation is used to map a HTTP PUT request to a specific handler method in the controller. It is equivalent to the following alternative.

 @RequestMapping(method = RequestMethod.PUT) 

@PatchMapping

This annotation is used to map a HTTP PATCH request to a specific handler method in the controller. It is equivalent to the following alternative.

 @RequestMapping(method = RequestMethod.PATCH) 

@RequestBody

This annotation is used to bind a method parameter/object to incoming request parameters.

\ @ResponseBody**

This is used inside a controller and signifies that the returned object will be automatically serialized and passed back into the HttpResponse object. Note that if you are using @RestController you may not need to use this as automatically it is a combination of @Controller and @ResponseBody.


@RequestParam

This is used to bind a method parameter directly to a request attribute.


@RequestHeader

This is used to bind a method parameter directly to a request header.


@RequestAttribute

This can be used to bind a method parameter to a request attribute that was added from an intermediary layer like filter or interceptor.


**@PathVariable
**This is used to bind a method parameter from a request template URI. Note that It can be used to bind multiple method parameters.

 package xyz.sumithpuri.spring.boot.annotation.controller;  
   
 import java.util.HashSet;  
   
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.web.bind.annotation.DeleteMapping;  
 import org.springframework.web.bind.annotation.GetMapping;  
 import org.springframework.web.bind.annotation.PathVariable;  
 import org.springframework.web.bind.annotation.PostMapping;  
 import org.springframework.web.bind.annotation.RequestBody;  
 import org.springframework.web.bind.annotation.RestController;  
   
 import xyz.sumithpuri.spring.boot.annotation.configuration.SBASampleConfigurationProperties;  
 import xyz.sumithpuri.spring.boot.annotation.model.Book;  
 import xyz.sumithpuri.spring.boot.annotation.service.BookServiceImpl;  
   
 /**  
  * @author Sumith Puri  
  *  
  */  
 @RestController  
 public class SBASampleController {  
   
      @Autowired  
      BookServiceImpl bookServiceImpl;  
   
      @Autowired  
      SBASampleConfigurationProperties sbasConfigProps;  
   
      @GetMapping("/findall")  
      public HashSet<Book> getAllBook() {  
           return bookServiceImpl.findAllBook();  
      }  
   
      @GetMapping("/findbyid/{id}")  
      public Book geBookById(@PathVariable long id) {  
           return bookServiceImpl.findBookByID(id);  
      }  
   
      @DeleteMapping("/delete")  
      public void deleteBook() {  
           bookServiceImpl.deleteAllData();  
      }  
   
      @PostMapping("/")  
      public void addBook(@RequestBody Book book) {  
   
           System.out.println("Testing Properties: " + sbasConfigProps.getName() + "; "   
                                                                  + sbasConfigProps.getMail() + "; "  
                                                                  + sbasConfigProps.getYear());  
           bookServiceImpl.addBook(book);  
      }  
 }  
   

Watch out for the next article in this series titled “SKP’s SB #05 : Spring Boot Annotation Reference-01/c”. “SKP’s SB Series” of Articles are entirely based on Spring Boot along with related topics like Docker Desktop, Java Timers, Spring Annotations and Clean Shutdown of Spring Boot Applications.

Also published here.


Written by sumithkpuri | Software Professional from India at the Level of a [Director of Engineering] or [Principal Architect].
Published by HackerNoon on 2023/01/05