Junior — Middle
What is the role of the @Component annotation in Spring and in which cases is it used?
sobes.tech AI
Answer from AI
The @Component annotation in Spring is used to mark a class as a component that should be automatically detected and registered in the Spring context as a bean. This allows Spring to manage the lifecycle of the object and inject it into other components.
@Component is used for classes that do not fall under more specialized stereotypes such as @Service, @Repository, or @Controller. For example, if you have a utility class or helper component that does not belong to the service layer or controllers, you can annotate it with @Component.
Example:
@Component
public class MyHelper {
public void doSomething() {
// logic
}
}
Then, this component can be injected into other beans using @Autowired.