Skip to main content

Spring Boot Annotations

Spring Boot Annotations :  As explained in my previous post Spring uses conditional interface to do auto configuration , below are the most common annotation used in Spring boot application. We will try to understand these annotations by developing a spring boot application from scratch.

We are going to create a restful webservice using spring Boot.

Generally there can be at least six or more packages as below :
  1. Configuration
  2. Controllers
  3. Services
  4. DAO
  5. Entities
  6. Utilities
1. Configuration ( To Enable Web security , Database Configuration , MQ Configuration )

To do so we will create our custom configuration class and annotate with @Configuration and for properties from configuration file @ConfigurationProperties("nameOfPropertiesIdentfier")

Inside that we will set all the required properties inside the bean of Respective configuration for example in case of Database , DataSource, JdbcTemplate etc.

First we need to put the below dependency then we need create a configuration class in which we will set properties of DataSource bean
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
DatabaseConfig.java for initialising DataSource bean with database properties , these properties will changes based on type like for MySql we need mysql driver and for Oracle we need Oracle Driver.

@Configuration
public class DatabaseConfig {

@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
Internally Spring will create EntityManager, TransactionManager beans , if we need to add some externalise properties then just like DataSource we need create methods with annotation @Bean and override the properties.

We can externalise the hardcoded properties by defining below key-value properties in our Application.yml by keeping key name as below. Only value should be change in case of different database.

Application.yml

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:test
spring.datasource.username=system
spring.datasource.password=system


Using @Profile annotation we can multiple Database configuration for all our different difficulties environment like DEV, UAT and PROD.

@Profile - Indicate which profile configuration should be loaded based on provided env value like dev, uat and prod.

Below are important annotations used in case of configuration 

   @Configuration - Indicates a class as a source of a bean
    @Bean - Indicates a method is producing a bean
    @Profile - Indicate which profile configuration should be loaded based on provided env value like dev, uat and prod.
    @Primary - Indicates primary bean in case of multiple configuration like Database.
    @PropertySource - Map properties file to the given configuration.
    @Value - Helps to read value from System environment. 

2 . Controller (After Filter and Security Dispatcher Servlet forward each request to their respective controller)

This is the main entry point of our application request after DispatcherServlet forward the request to Respective Controller .
Just consider below snippet from a controller 
@RestController
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

@RequestMapping(value = "/getEmployee/{id}",method = RequestMethod.GET)
public String getEmployee(@PathVariable long id)
{
return employeeService.getEmployee(id).toString();

}

Below are important annotations used in case of controller 

     @RestController - Indicates a controller with default return type of JSON
     @RequestMapping - Indicates the mapping of methods to each HTTP request(GET,POST,PUT,DELETE)
     @RequestParam - Map requested key-value pair from URI to input param of controller methods
     @PathVariable - Map URI value to input param of controller methods
     @RequestBody - Map Requested JSON input to input param of controller methods as Object of mentioned type.
     
3. Services (Controller will delegate the request to service class which should be @Autowired in Respective Controller classes )

     @Service annotation will be used for Service class in which we will have method of DAO layer by @Autowiring the respective DAO class. Below is the snippet from a service class.

@Service
public class EmployeeService {

@Autowired
private EmployeeJpa employeeJpa;

public Employee saveEmployee(Employee employee)
{
employeeJpa.save(employee);
return employee;

}

public Employee getEmployee(long id) {

return employeeJpa.getById(id);
}

4. DAO (Service will delegate the request to DAO class which should be @Autowired in Respective Service classes )

    @Repository will be used to indicate that this is a DAO class, we can extend any Spring repository Interface like CRUDREPOSITORY or JPAREPOSITORY by defining entity class name and Primary id type of Entity class. After doing this our custom DAO interface will have all the lexical kind of generics methods  implemented internally we don't need to write the implementation for these methods . 
@Repository
public interface EmployeeJpa extends JpaRepository<Employee, Long> {
}

Below are some example of methods :
  1. findById(int id)
  2. findAll()
  3. findByIntancVariableName()
  4. save()
  5. delete()
Now directly we can autowire our custom DAO interface in Service class and can call these methods.


5. Entity( DAO will use these entities for CRUD operation like save get update delete )

This is main Resource for which we have created all configuration , service and DAO layer. In spring boot it represents a Table of Database, below is snippet of Employee Table .

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long id;
String name;
String dept;
String company;
long mobile;
}

    @Entity - Indicates the class as an table instance of Database
    @Id - Used for primary key column
    @GeneratedValue(strategy= GenerationType.AUTO) - Primary key generation Strategy
    @Column - Used for define column properties like length, unique, nullable etc 
    
We can have some utility package for parsing and all.

That's all , we can start the application and you can do CRUD operation on Resources present in Database.

Below are some important Spring Boot Annotations in sequence of use while creating RESTful API with short description .

    @Componant - Indicates a class as Spring bean while doing Auto-Scan, 
    @Controller,@Service and @Respository are the specialisation of @Componant.

    @Autowired - Inject appropriate bean to the class member, it can be done by 3 ways
         1) Constructor - For required value of class (Best option )
         2) Setter method - For Optional  value of class.
         3) Class member - For Optional  value of class.

    @Qualifier - Filter what bean should be used to auto wired a Field or Parameter.
    @Scope- By default it will be Singleton , we can make scope as ProtoType, request, session and Global session
    @Lazy - Indicates a bean or component initialise on demand  


@RequestMapping > @RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)

 @RequestBody > @PostMapping("/save") void saveVehicle(@RequestBody Vehicle vehicle)

 @PathVariable > @RequestMapping("/{id}") 

Vehicle getVehicle(@PathVariable("id") long id) 
Vehicle getVehicle(@PathVariable(required = false) long id) for optional 

@RequestParam > 

Vehicle getVehicleByParam(@RequestParam("id") long id) 
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) 
we can specify an injected value when Spring finds no or empty value in the request. 

@ResponseBody > @ResponseBody @RequestMapping("/hello") 
If we mark a request handler method with @ResponseBody, Spring treats the result of the method as the response itself: If we annotate a @Controller class with this annotation, all request handler methods will use it. 

@ExceptionHandler > @ExceptionHandler(IllegalArgumentException.class) 
void onIllegalArgumentException(IllegalArgumentException exception)
 { With this annotation, we can declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions. The caught exception can be passed to the method as an argument: }

@ResponseStatus > @ExceptionHandler(IllegalArgumentException.class)

 @ResponseStatus(HttpStatus.BAD_REQUEST) 
void onIllegalArgumentException(IllegalArgumentException exception) 
{ We can specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument. }

 @RestController > The @RestController combines @Controller and @ResponseBody. 

@ModelAttribute > @PostMapping("/assemble") 
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) 
With this annotation we can access elements that are already in the model of an MVC @Controller, by providing the model key

@ModelAttribute("vehicle") > Besides, @ModelAttribute has another use: if we annotate a method with it, Spring will automatically add the method’s return value to the model: 

@CrossOrigin > @CrossOrigin enables cross-domain communication for the annotated request handler methods

Will request you to go through previous post of Spring Boot to understand it in more detail.


Comments

Popular posts from this blog

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control Java flight recording(JFR) help us to analyse and find the root cause of any slowness in our program along with CPU usage , hot methods and garbage collection , profiling etc. To visualise we need to feed .jfr file to JDK mission control present in JDK bin folder. After successful compilation , we should run the program with below option which will generate the .jfr and feed to mission control.   command :  j ava -XX:+UnlockCommercialFeatures -XX:+FlightRecorder  -XX:StartFlightRecording=duration=200s,filename=flight.jfr -cp ./out/ path-and-class-name Below are some example to understand how this JFR can be helpful. 1. Lets consider we have created a java program in which we have used LinkList to store the elements and in same program we are using contains method inside a for loop of 1 million , in this case each time this contains method will be called then 1 million records will be sc...