Junior — Middle
118
Hoe voer je dependency injection uit in Spring voor een specifiek veld van een interface, als deze twee implementaties heeft?
Bedrijven waar gevraagd werd
ITFB Group
Antwoord van AI
sobes.tech AI
В Spring, если у интерфейса есть две реализации, и нужно внедрить зависимость по конкретному полю, можно использовать аннотацию @Qualifier для указания, какую именно реализацию нужно внедрить.
Пример:
public interface Service {
void execute();
}
@Service
@Qualifier("serviceA")
public class ServiceA implements Service {
public void execute() { /* реализация A */ }
}
@Service
@Qualifier("serviceB")
public class ServiceB implements Service {
public void execute() { /* реализация B */ }
}
@Component
public class Client {
private final Service service;
@Autowired
public Client(@Qualifier("serviceA") Service service) {
this.service = service;
}
}
Таким образом, с помощью @Qualifier можно явно указать, какую реализацию внедрять, если их несколько.