Spring Boot Notes:: List of Annotations
Spring Boot Notes:: List of Annotations
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.
@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.
@RequestMapping("/admin")
@RequestMapping("/adminPanel")
public String adminPanel() {
return "adminPanel.html";
@RequestMapping("/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.
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.) :
// some code
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:
String helloWorld() {
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}")
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;
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
{
"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){
return dept;
}
With @ResponseBody, only the body is returned. The headers and status code are provided by
Spring.t
<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);
}
}
bootstrap.properties
#Server port
server.port = 8888
#Git repo location
spring.cloud.config.server.git.uri= // remote git-repo location
Add dependency :
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2. Add @EnableCircuitBreaker annotation
3. Add @EnableHystrixDashboard annotation
4. Add annotation @HystrixCommand(fallbackMethod = "myFallbackMethod")
Spring Profile:
For example, you can declare properties files like application-propduction.properties or application-
production.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