Interview Question - Important Spring Annotations to create REST API's
Essential Spring Annotations for REST API Development
Spring is a popular Java framework that simplifies the development of Java applications, including the creation of RESTful APIs. Here are some basic Spring annotations used in building a REST API along with brief descriptions:
Annotations for REST API:
@RestController
@RequestMapping
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping
@PathVariable
@RequestBody
@RequestParam
Annotations for Component Scanning:
@Service
@Repository
@Component
Annotations for Exception Handling:
@ControllerAdvice
@ExceptionHandler
@ResponseStatus
@RestControllerAdvice
1. Annotation: @RestController:
Description: This
annotation is used to define a class as a RESTful controller. It combines the
functionality of `@Controller` and `@ResponseBody`, indicating that the
returned value from the methods should be directly written into the response
body.
Example
@RestController
public class
MyController {
// Controller
methods go here
}
2. Annotation: @RequestMapping:
Description: This
annotation is used to map HTTP requests to handler methods in the controller.
It can be applied at the class level to specify a base URI for the entire
controller, and at the method level to define specific URI patterns.
Example
@RestController
@RequestMapping("/api")
public class
MyController {
@RequestMapping("/endpoint")
public String
myEndpoint() {
// Method
logic
return
"Hello, World!";
}
}
3. Annotation: @GetMapping, @PostMapping, @PutMapping,
@DeleteMapping:
Description: These
annotations are shortcuts for `@RequestMapping` with the HTTP methods GET,
POST, PUT, and DELETE respectively. They are used to define handler methods for
specific HTTP methods.
Example
@RestController
@RequestMapping("/api")
public class
MyController {
@GetMapping("/get")
public String
getData() {
// Method
logic
return
"Data retrieved!";
}
@PostMapping("/post")
public String
postData() {
// Method
logic
return
"Data posted!";
}
}
4. Annotation: @PathVariable:
Description: This
annotation is used to extract values from the URI and bind them to method
parameters. It is often used to capture template variables in the URI.
Example
@RestController
@RequestMapping("/api")
public class
MyController {
@GetMapping("/user/{id}")
public String
getUser(@PathVariable Long id) {
// Method
logic
return
"User ID: " + id;
}
}
5. Annotation: @RequestBody:
Description: This
annotation is used to bind the HTTP request body to a method parameter. It is
commonly used to handle data sent in the request body, such as JSON or XML.
Example
@RestController
@RequestMapping("/api")
public class MyController
{
@PostMapping("/user")
public String
createUser(@RequestBody User user) {
// Method
logic
return
"User created: " + user.getName();
}
}
6. Annotation: @RequestParam
Description: This annotation
in Spring is used to extract query parameters from the request URL and bind
them to method parameters. Here's an example of how to use `@RequestParam`:
Example
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/greet")
public String
greetUser(@RequestParam(name = "name", defaultValue =
"Guest") String userName) {
// Method
logic
return
"Hello, " + userName + "!";
}
}
In this example:
- `@RequestParam` is used to bind the value of the query
parameter "name" to the `userName` method parameter.
- The `name` attribute in `@RequestParam` specifies the name
of the query parameter.
- The `defaultValue` attribute provides a default value for the parameter if it is not present in the request.
For instance, if you send a GET request to `/api/greet` without any query parameters, the `userName` parameter will default to "Guest". If you send a request like `/api/greet?name=John`, then `userName` will be bound to "John".
Certainly! In Spring, `@Service`, `@Repository`, and
`@Component` are stereotypes that define the roles of the annotated classes.
These annotations are used to indicate the purpose of a class within the
application and enable Spring to automatically discover and manage these
components. Here's a brief description of each:
7. Annotation: @Service:
Description: This annotation is used to indicate that a
class is a service class. Service classes in Spring typically contain business
logic and are used to perform operations, manipulate data, or orchestrate the
flow of the application. Service classes are often used in the service layer of
a Spring application.
Example:
@Service
public class
MyService {
// Service
methods go here
}
8. Annotation: @Repository:
Description: This annotation is used to indicate that a
class is a repository class. Repository classes in Spring are responsible for
data access, database interactions, and generally encapsulate the logic to
interact with a data source. It is commonly used in the data access layer of a
Spring application.
Example:
@Repository
public class
MyRepository {
// Repository
methods go here
}
9. Annotation: @Component:
Description: This is a generic stereotype annotation
indicating that a class is a Spring component. It is a general-purpose
stereotype and is often used when the purpose of a class doesn't fit into the
more specific categories of `@Service` or `@Repository`. Components are
typically used as general-purpose beans that don't fall into more specific
categories.
Example:
@Component
public class
MyComponent {
// Component
methods go here
}
These annotations play a crucial role in the Spring
framework's component scanning mechanism. When you annotate a class with
`@Service`, `@Repository`, or `@Component`, Spring automatically detects and
registers these classes as Spring beans, making them available for dependency
injection and other Spring features.
Remember that the specific choice between `@Service`,
`@Repository`, or `@Component` often depends on the role or purpose of the
class within your application. The primary distinction is more semantic than
functional, but it helps in organizing and understanding the responsibilities
of different classes within your codebase.
In Spring, there are several annotations related to
exception handling that help you handle exceptions in a more organized and
centralized manner. Here are some commonly used annotations:
10. Annotation: @ControllerAdvice:
Description: This annotation is used to define a global
exception handler for the entire application. It allows you to consolidate your
exception handling logic in one place and apply it across multiple controllers.
Example:
@ControllerAdvice
public class
GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public
ResponseEntity<String> handleException(Exception ex) {
// Handle
the exception
return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error
occurred");
}
}
11. Annotation: @ExceptionHandler:
Description: This annotation is used within a class
annotated with `@ControllerAdvice` to define methods that handle specific
exceptions. Each method annotated with `@ExceptionHandler` will handle a
particular type of exception.
Example:
@ControllerAdvice
public class
GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public
ResponseEntity<String>
handleResourceNotFoundException(ResourceNotFoundException ex) {
// Handle
the specific exception
return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
12. Annotation: @ResponseStatus:
Description: This annotation is used to specify the HTTP
status code to be returned when a specific exception is thrown. It can be used
in conjunction with `@ExceptionHandler`.
Example:
@ControllerAdvice
public class
GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String
handleResourceNotFoundException(ResourceNotFoundException ex) {
// Handle
the exception, no need to return ResponseEntity
return
ex.getMessage();
}
}
13. Annotation: @ControllerAdvice + @RestControllerAdvice:
Description: While `@ControllerAdvice` is designed for
traditional MVC controllers returning views, `@RestControllerAdvice` is
tailored for RESTful controllers returning data. It combines
`@ControllerAdvice` and `@ResponseBody`.
Example:
@RestControllerAdvice
public class
GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public
ResponseEntity<String> handleException(Exception ex) {
// Handle
the exception for RESTful controllers
return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error
occurred");
}
}
These annotations allow you to define a centralized and consistent approach to handle exceptions in your Spring application. By using `@ControllerAdvice` and `@ExceptionHandler`, you can customize the response for different types of exceptions, making your exception handling logic more modular and maintainable.
These are just a few of the basic annotations in Spring for
building RESTful APIs. There are many more annotations and features provided by
the Spring framework to handle various aspects of RESTful service development,
such as content negotiation, exception handling, and security.
Tags: REST API Development , Spring Annotations , Spring API Development , Spring REST API
Get Updates
Subscribe to our e-mail to receive updates.
0 Responses to “Interview Question - Important Spring Annotations to create REST API's”
Post a Comment
Thanks for your comments