Junior — Middle
Can you explain the concept of a component in Spring and how it is used in applications?
sobes.tech AI
Answer from AI
In Spring, a component is an object managed by the Spring container (IoC container). The @Component annotation is used to mark a class as a component so that Spring automatically creates its instance and injects dependencies.
Components enable the implementation of the Inversion of Control (IoC) principle and facilitate dependency management.
Example:
import org.springframework.stereotype.Component;
@Component
public class MyService {
public void doWork() {
System.out.println("Work completed");
}
}
This component can then be injected into other classes using @Autowired:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
private final MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
}
public void process() {
myService.doWork();
}
}
Thus, components simplify code organization and dependency management in an application.