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

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ;

OOPS Concept in Java : ENCAPSULATION

OOPS Concept in Java : ENCAPSULATION   This OOPS concept can be used to make things simpler in case of software development . Main purpose of this concept is to hide the properties of any class and give access to fetch and modified based on business criteria.  A simple example can be a POJO ( Plain Old Java Object) in which all the properties of a class can be private and through getter and setter method of properties we can fetch and update the properties of Object. So instead of having direct access to properties we have created 2 methods to make the CLASS things encapsulated in single unit while access to it is via 2 public methods.   Just consider we have requirement that once the object is created its value should not be changed then simplest way to achieve this  can be done by just removing setter method and we will keep only getter methods to access Object properties . In this case after Object creation whatever the value of Object properties has been initialised it will b

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If Object is of PARENT