Junior — Middle
What steps need to be taken to implement a component in Spring using dependency injection?
sobes.tech AI
Answer from AI
To implement a component in Spring using dependency injection, follow these steps:
-
Declare the component:
- Annotate the class with
@Component,@Service,@Repository, or another suitable annotation to let Spring recognize it as a bean.
- Annotate the class with
-
Enable component scanning:
- Ensure that the package containing the component is scanned by Spring (for example, using
@ComponentScanin the configuration).
- Ensure that the package containing the component is scanned by Spring (for example, using
-
Inject the dependency:
- In the class where the component is needed, declare a field or constructor with a parameter of the required type.
- Use the
@Autowiredannotation for automatic injection.
Example:
@Component
public class MyService {
public void doWork() { /*...*/ }
}
@Component
public class MyController {
private final MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
}
public void process() {
myService.doWork();
}
}
This way, Spring will automatically create and inject an instance of MyService into MyController.