Junior — Middle
Kas saaksite selgitada komponendi kontseptsiooni Springis ja kuidas seda rakendustes kasutatakse?
sobes.tech AI
Vastus AI-lt
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 the application.