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.
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.
2 . Controller (After Filter and Security Dispatcher Servlet forward each request to their respective controller)
@RequestMapping > @RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)
Generally there can be at least six or more packages as below :
- Configuration
- Controllers
- Services
- DAO
- Entities
- 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.
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 :
- findById(int id)
- findAll()
- findByIntancVariableName()
- save()
- 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
@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
Post a Comment