Video tayyorlanmoqda
Service Locator nima va nega u Dependency Injection'dan yomonroq?
Service Locator — klass o'ziga kerakli bog'liqlikni markaziy registry'dan o'zi so'rab oladi (context.getBean(...)). Ishlaydi, lekin bog'liqliklar konstruktorda ko'rinmaydi, testda registry'ni sozlash kerak bo'ladi va xato faqat runtime'da chiqadi.
📖 Javob
@Service
class ReportService {
@Autowired private ApplicationContext ctx;
public byte[] export(String format) {
var exporter = ctx.getBean(format + "Exporter", Exporter.class); // locator
var repo = ctx.getBean(ReportRepository.class);
return exporter.export(repo.load());
}
}
Muammolar:
- klass qaysi bean'larga bog'liqligini faqat ichini o'qib bilasiz;
- testda
new ReportService()qilib bo'lmaydi — butun kontekst yoki mockApplicationContextkerak; "pdfExporter"bean nomi xato yozilsa —NoSuchBeanDefinitionExceptionfaqat shu tarmoq ishlaganda;- kod Spring API'siga bog'lanib qoladi.
DI varianti — xuddi shu dinamik tanlov bilan:
@Service
class ReportService {
private final Map<String, Exporter> exporters; // bean nomi -> bean
private final ReportRepository repo;
ReportService(Map<String, Exporter> exporters, ReportRepository repo) { ... }
public byte[] export(String format) {
var e = exporters.get(format + "Exporter");
if (e == null) throw new UnsupportedFormatException(format);
return e.export(repo.load());
}
}
Bog'liqliklar ko'rinib turibdi, testda oddiy Map.of(...) beriladi.
Locator normal bo'lgan joylar: framework infratuzilmasi, ObjectProvider<T> orqali lazy yoki prototype bean olish, ServiceLoader bilan plugin yuklash. Biznes kodida esa getBean ko'rsangiz — bu DI'ni chetlab o'tish belgisi.
Ro'yxatdan o'ting, shunda o'rgangan savollaringiz belgilanadi va progressingiz saqlanadi.