StereoType Annotations Flashcards
@Component
The most general stereotype annotation, used to denote a class as a Spring-managed component.It’s typically used when a class doesn’t specifically belong to one of the other roles like a service or controller.
What is
stereotype annotations are special annotations that indicate a class is a Spring-managed component with a specific role within the application’s architecture
@Service
Specialization of @Component, specifically intended for service layer classes.
@Repository
Provides additional persistence-related exception handling, allowing for the conversion of database-related exceptions into Spring’s DataAccessException
@Controller
Typically used for classes that handle incoming HTTP requests and return views or responses.
Often paired with @RequestMapping methods to handle specific HTTP routes.
@RestController
Combines @Controller and @ResponseBody.
Typically used for RESTful web services, returning JSON or XML responses instead of views.
@RestController
public class MyRestController {
@GetMapping(“/api/greet”)
public String greet() {
return “Hello, RESTful World!”;
}
}
Working
When Spring scans for beans using @ComponentScan, it looks for classes annotated with any stereotype annotation. Once detected, these classes are registered in the application context and managed as Spring beans. This automatic registration enables dependency injection and supports Spring’s inversion of control (IoC) capabilities.