Sobes.tech
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:

  1. Declare the component:

    • Annotate the class with @Component, @Service, @Repository, or another suitable annotation to let Spring recognize it as a bean.
  2. Enable component scanning:

    • Ensure that the package containing the component is scanned by Spring (for example, using @ComponentScan in the configuration).
  3. 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 @Autowired annotation 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.