Sobes.tech
Senior

How does Spring inject all implementations of an interface into a service?

sobes.tech AI

Answer from AI

Spring can inject all implementations of an interface into a service using collections, such as List or Set. To do this, a field or constructor parameter with the collection type of the interface is declared in the service, and Spring automatically provides all beans implementing this interface.

Example:

@Service
public class MyService {
    private final List<MyInterface> implementations;

    public MyService(List<MyInterface> implementations) {
        this.implementations = implementations;
    }

    public void doWork() {
        for (MyInterface impl : implementations) {
            impl.execute();
        }
    }
}

Here, Spring finds all beans implementing MyInterface and passes them to the constructor as a list. This is convenient for plugins or extendable components.