Sobes.tech
Junior — Middle

In which cases should you apply the @Component annotation in your Spring application?

sobes.tech AI

Answer from AI

The @Component annotation in Spring is used to mark a class as a component managed by the Spring container. This allows for automatic instantiation of the class and its injection into other components.

Use @Component when:

  • The class does not fit more specialized stereotypes (@Service, @Repository, @Controller).
  • You want Spring to automatically detect and register the bean through component scanning.

Example:

@Component
public class MyUtility {
    public void doSomething() {
        // logic
    }
}

Thus, @Component is a universal way to declare a class as managed by Spring, especially for auxiliary or common components.

In which cases should you apply the @Component… - sobes.tech