Junior — Middle
Can you explain the differences between the annotations @Controller and @Component in Spring, and their purpose?
sobes.tech AI
Answer from AI
In Spring, @Component is a generic annotation used to denote a class as a component that will be managed by the Spring container (IoC). It is used for automatic detection and registration of beans.
@Controller is a specialized annotation that extends @Component and indicates that the class is intended to handle HTTP requests in an MVC application. Classes with @Controller typically contain methods with annotations like @RequestMapping for routing.
Thus:
@Componentis a general stereotype for components.@Controlleris a specialized component for web controllers.
Example:
@Component
public class MyService {
// business logic
}
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "hello";
}
}