Java - Spring to inject multiple service instances having same interface

less than 1 minute read

Create service for multiple name providers

1
2
3
4
5
6
7
8
9
10
11
interface NameProvider {
    String name();
}
@Service
public class SomeName implement NameProvider {
    public String name() { return "SomeName"; }
}
@Service
public class AnotherName implement NameProvider {
    public String name() { return "AnotherName"; }
}

NameService class can inject multiple NameProviders with the following constructor injection.

1
2
3
4
5
6
7
@Service
public class NameService {
    private List<NameProvider> nameProviders;
    NameService(List<NameService> nameProviders) {
        this.nameProviders = nameProviders;
    }
}