Spring Boot Notes:
List of Annotations:
Details:
- If we add @SpringBootApplication annotation to class then we do not need to add
@EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The
@SpringBootApplication annotation includes all other annotations.
@EnableAutoConfiguration: Spring Boot Auto Configuration automatically configures your Spring
application based on the JAR dependencies you added in the project. For example, if MySQL database is
on your class path, but you have not configured any database connection, then Spring Boot
autoconfigures an in-memory database.
@ComponentScan: The @ComponentScan enables component scanning so that controller or any other
component class you create will be automatically discovered and registered with Spring Bean.
@Configuration: is a marker annotation which indicates that a class declares one or more @Bean
methods and may be processed by the Spring container to generate bean definitions and service
requests for those beans at runtime.
Spring Actuator:
Spring boot’s module Actuator allows you to monitor and manage application usages in production
environment, without coding and configuration for any of them. These monitoring and management
information is exposed via REST like endpoint URLs.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
There is a /health endpoint that provides basic information about the application’s health. The /metrics
endpoint shows several useful metrics information like JVM memory used, system CPU usage, open
files, and much more.
@RequestMapping:
It is one of the basic annotations in Spring which maps HTTP requests (URLs) with methods.
The mapping can be assigned at a class level or a method level.
@RequestMapping("/admin")
public class AdminController() {
@RequestMapping("/adminPanel")
public String adminPanel() {
return "adminPanel.html";
@RequestMapping("/statistics")
public String statistics() {
return "statistics.html";
Here, the /admin mapping is assigned on the class level, whereas the /adminPanel and /statistics
mappings are assigned to methods. The class-level mapping will be used as a prefix for all of these
method-level mappings: /admin/adminPanel and /admin/statistics.
Multiple Mappings per Method
@RequestMapping({"/", "/index", "/home"})
public void helloWorld() {
return "Hello World!";
Request Methods
The most common attribute used is the method attribute which allows us to specify and narrow down
the request method that our method handles (GET, POST, DELETE, etc.) :
@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProductPost(@ModelAttribute("product") Product product) {
// some code
If we don't specify a request method, the default request method is GET.
Request Headers:
We can further specify the mapping by defining one or more headers. In this case, the helloWorld()
method will handle the request if its content-type is text/plain or text/html:
@RequestMapping(value = "/header", headers = {"content-type=text/plain",
"content-type=text/html"})
String helloWorld() {
return "Hello World!";
Path Variables:
A lot of websites rely on path variables to showcase a specific product, page, profile, etc. to the end-
user, such as example.com/viewProduct/324, where 324 is the product ID:
@RequestMapping("/viewProduct/{productId}")
public String viewProduct(@PathVariable int productId, Model model) {
Product product = productService.getProductById(productId);
model.addAttribute("product", product);
return "viewProduct";
Request Param:
As the name suggests, @RequestParam is used to get the request parameters from URL, also known as
query parameters, while @PathVariable extracts values from URI.
For example, if the incoming HTTP request to retrieve a book on topic "Java"
is http://localhost:8080/shop/order/1001/receipts?date=12-05-2017, then you can use
the @RequestParam annotation to retrieve the query parameter date and you can
use @PathVariable to extract the orderId i.e. "1001" as shown below:
@RequestMapping(value="/order/{orderId}/receipts", method =
RequestMethod.GET)
public List listUsersInvoices( @PathVariable("orderId") int
order,
@RequestParam(value = "date", required = false) Date dateOrNull)
{
...
}
ResponseEntity, ResponseBody,
ResponseEntity represents an HTTP response, including headers, body, and status in a spring restful
API. While @ResponseBody puts the return value into the body of the response of
API, ResponseEntity also allows us to add headers and status code as well.
Prerequisite :
Let’s take a Java Entity Model Class called “Dependant” to be used in this example.
@Entity
@Table(name = "Dependant")
public class Dependant implements Serializable {
@Id
private int deptid;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
// getter, setter methods ...
}
ResponseEntity
Let’s create a simple REST API which returns Dependant class object which we made above, wrapped
inside the ResponseEntity.
@GetMapping("/dependant/id/{id}")
public ResponseEntity<Dependant> getDependantbyId(@PathVariable int id){
Dependant dept = new Dependant();
dept = dependantRepository.findBydeptid(id);
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo - Department");
return ResponseEntity.status(HttpStatus.OK).headers(headers).body(dept);
}
We give ResponseEntity a custom status code, headers, and a body.
OUTPUT
Status : 200 OK
Custom-Header →foo - Department
Content-Type →application/json;charset=UTF-8
Transfer-Encoding →chunked
Date →Tue, 25 Feb 2020 07:48:58 GMT
and body as shown below
{
"deptid": 1,
"firstname": "Donald",
"lastname": "T",
}
ResponseBody
In this example we try to achieve the same as as ResponseEntity but @ResponseBody only returns the
body, in this case only the Dependant class object.
@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependant2byId(@PathVariable int id){
Dependant dept = new Dependant();
dept = dependantRepository.findBydeptid(id);
return dept;
}
With @ResponseBody, only the body is returned. The headers and status code are provided by
Spring.t
Spring Cloud Configuration Server
Create Cloud Config Server
Step 1 . Add Below dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Step2.
Now, add the @EnableConfigServer annotation in your main Spring Boot application class file. The
@EnableConfigServer annotation makes your Spring Boot application act as a Configuration Server.
@SpringBootApplication
@EnableConfigServer
public class ConfigserverApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigserverApplication.class, args);
}
}
3. Point the Git repo from Config Server
Create one file called bootstrap.properties in the src\main\resources directory of spring-config-sever
project and add below lines.
bootstrap.properties
#Server port
server.port = 8888
#Git repo location
spring.cloud.config.server.git.uri= // remote git-repo location
Config Client Configuration
Add dependency :
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Bind with the Config Server in bootstrap.properties
spring.cloud.config.uri=http://localhost:8888 [Config Server End Point]
Hystrix Circuit Breaker Pattern – Spring Cloud
It is generally required to enable fault tolerance in the application where
some underlying service is down/throwing error permanently, we need to fall
back to different path of program execution automatically. This is related to
distributed computing style of Eco system using lots of underlying
Microservices. This is where circuit breaker pattern helps and Hystrix is an
tool to build this circuit breaker.
Hystrix configuration is done in four major steps.
1. Add Hystrix starter and dashboard dependencies.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
2. Add @EnableCircuitBreaker annotation
3. Add @EnableHystrixDashboard annotation
4. Add annotation @HystrixCommand(fallbackMethod = "myFallbackMethod")
Spring Profile:
Spring Boot Environment Specific Properties
For example, you can declare properties files like application-propduction.properties or application-
production.properties.
Application properties naming scheme: application-{spring_active_profile}.properties.
application.properties
spring.profiles.active=dev
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
application-dev.properties
spring.datasource.url= jdbc:mysql://dev_db_host:3306/songsDB