Junior — Middle
Do you apply the @Component annotation when declaring classes as beans in Spring?
sobes.tech AI
Answer from AI
Yes, the @Component annotation in Spring is used to mark a class as a component that will be automatically detected and registered in the Spring context as a bean.
However, more specialized annotations are often used, which are derived from @Component:
@Service— for service classes,@Repository— for data access classes,@Controller— for MVC controllers.
Using @Component is justified when the class does not fit more specific stereotypes or for creating custom components.
Example:
import org.springframework.stereotype.Component;
@Component
public class MyBean {
// class logic
}
Thus, @Component is a basic annotation for bean registration, but in practice, it is often preferable to use more specific annotations.