Advertisement
Google Ad Slot: content-top
Spring Boot Annotations
Spring Boot provides powerful annotations to simplify development. Here’s a categorized list with explanations and examples.
@SpringBootApplication
Marks the main class of a Spring Boot application.
Internally includes:
@Configuration– Marks a configuration class@EnableAutoConfiguration– Enables auto-configuration@ComponentScan– Scans for Spring components
@Controller (Web Layer - MVC)
@Controller is a Spring MVC annotation that marks a class as a web controller handling HTTP requests.
✅ Best Use Case: Use @Controller for handling MVC views (Thymeleaf, JSP, etc.).
@RestController
A combination of @Controller + @ResponseBody, used for REST APIs.
Difference between @Controller and @RestController:
@Controlleris used for MVC-based web applications (returns views).@RestControlleris used for RESTful APIs (returns JSON/XML responses).
@Service (Business Logic Layer)
@Service is a specialized version of @Component, specifically for service-layer logic. It indicates that a class contains business logic.
✅ Best Use Case: Use @Service for business logic or service classes that interact with repositories.
@Entity, @Table, @Column
Used for Hibernate/JPA entity mapping.
@Repository (Data Access Layer)
@Repository is a specialized @Component used for database access logic.
It is mainly used with Spring Data JPA and Hibernate.
✅ Best Use Case: Use @Repository for DAO (Data Access Object) classes that interact with the database.
- Converts JPA exceptions into Spring DataAccessException.
- Works seamlessly with Spring Data JPA.
@RequestMapping
- A general-purpose annotation used to map HTTP requests to specific methods.
- Can handle all HTTP methods (GET, POST, PUT, DELETE, etc.).
- Supports attributes like
path,method,produces, andconsumes.
🔹 Alternative: Instead of @RequestMapping(method = RequestMethod.GET), you can use @GetMapping, which is more specific.
@GetMapping
- Specifically used for handling GET requests.
- Used for retrieving data from the server.
@PostMapping
- Used to handle POST requests.
- Typically used for creating new resources.
✔ Can also accept request body using @RequestBody
@PutMapping
- Used for updating an existing resource.
- Handles PUT requests.
@DeleteMapping
- Used to delete a resource.
- Handles DELETE requests.
@PathVariable & @RequestParam
Extracts values from the URL path or query parameters.
@Valid & @Validated
Used for validating request body data.
@Autowired
Injects a dependency automatically.
@Qualifier
Used when multiple beans of the same type exist.
@Primary
Marks a bean as the default when multiple beans of the same type exist.