Spring Core & Dependency Injection interview questions & answers
205+ real Spring Core & Dependency Injection interview questions with model answers, plus free lessons to learn the concepts. Prepare in English & Hinglish, then practise with an AI mock interview.
18 topics · 205+ questions
Hirenix kaise padhata hai
Ek chapter. 90 minute.
Interview ke liye taiyaar.
Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.
- 📖Concept, 5 min meinJargon nahi — seedhi baat
- 🛠️Real-world problemJaisa production code mein aata hai
- 💬Model answerInterview mein kya bolna hai
- 🧠FlashcardsRevision 10 min mein
- 🤖AI mock interviewFollow-up bhi poochta hai
- 📊Weak topicsKahan phans rahe ho, pata chale

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.
What you’ll learn
- ●Spring kyun: IoC aur Dependency Inversion Principle
- ●Dependency injection: constructor vs setter vs field
- IoC container: BeanFactory aur ApplicationContextFree account
- Bean definitions: XML, Java config, aur component scanFree account
- Bean scopes: singleton, prototype, aur web scopesFree account
- Bean lifecycle: PostConstruct, PreDestroy, InitializingBeanFree account
- Autowiring, ambiguous beans, Qualifier aur PrimaryFree account
- Component scanning aur stereotypes: Component, Service, RepositoryFree account
- Java config (Configuration/Bean) vs annotation configFree account
- Property sources, Value, aur ConfigurationPropertiesFree account
- Spring Profiles: environment ke hisaab se beansFree account
- Circular dependency problem aur LazyFree account
- AOP basics: cross-cutting concerns aur proxiesFree account
- BeanPostProcessor vs BeanFactoryPostProcessorFree account
- RecapFree account
- ●Project: Configurable Notification Service
- Project: Pluggable Discount Strategy with DIFree account
- Project: Lifecycle-Audited Resource PoolFree account
Spring kyun: IoC aur Dependency Inversion Principle
Aapne new hazaar baar likha hai. Spring ka pehla poora sabak sirf un chand jagahon ke baare me hai jahan new likhna galti ban jaata hai.
Ek class dekhiye jo order confirmation bhejti hai. OrderService ke andar kisi ne likh diya: private final MessageSender sender = new EmailSender();. Chal raha hai, ship bhi ho gaya. Phir product wale kehte hain ki ab confirmation SMS se jaayega. Ab aapko OrderService kholni padegi — wo class jiska kaam orders hai, jise email ya SMS se koi matlab hi nahi — aur usme edit karna padega. Us edit ka orders se koi lena-dena nahi. Yahi tight coupling hai: OrderService ne apne collaborator ko sirf use nahi kiya, usne chuna — aur chunte hi dono ek doosre se chipak gaye.
Doosra nuksaan zyada chupa hua aur zyada bada hai. OrderService ka unit test likhne ke liye ab sach me email bhejni padegi, kyunki jis object se wo baat karti hai wo uske andar hardcode hai. Fake ghusane ke liye koi jagah hi nahi bachi.
Inversion of Control (IoC) iska ilaaj hai, aur naam khud bata deta hai ki kya ulta ho raha hai. Aam taur par class khud tay karti hai ki uske concrete collaborators kaun honge — wo new bulati hai. Isko ulta kar dijiye: class sirf bata degi ki use kya chahiye, aur kaun dega ye koi aur tay karega. Dependency Injection (DI) wahi tareeqa hai jisse ye kiya jaata hai — dependency bahar se andar bheji jaati hai, aam taur par constructor se. IoC usool hai; DI uska tareeqa. Interview me aapse yahi do shabd alag karke bolne ko kaha jaata hai, isliye inhe alag rakhiye.
Ek teesra shabd inke saath lagataar gadbad karta hai. Dependency Inversion Principle (SOLID ka D) ek design rule hai: abstraction par depend karo, concrete par nahi — yaani OrderService ko MessageSender interface pakadna chahiye, EmailSender nahi. Dependency Injection wo mechanism hai jo runtime par concrete instance pahunchata hai. Aap bina kisi framework ke, haath se interface constructor me pass karke, principle follow kar sakte hain. Spring aapko principle nahi deta; principle aap follow kar lein to wiring ka kaam Spring automate kar deta hai.
To Spring ka container asal me hai kya? Wo ek object hai jo aapki configuration padhta hai, aapke objects banata hai, kaun kis par depend karta hai ye nikaalta hai, aur har ek ko uske collaborators thama deta hai. Aapka code wapas ye batane lagta hai ki use kya chahiye, aur ek hi jagah — configuration — ye batati hai ki milega kya.
Container kab uthana chahiye: jab wahi object graph ek se zyada jagah banta ho, jab wiring environment ke hisaab se badalti ho (production me asli payment gateway, test me stub), ya jab aapko kisi class ka unit test uski poori dependency-tree ghaseete bina likhna ho. Neeche wale demo me email se SMS par jaane ke liye sirf configuration badli — OrderService kholi tak nahi gayi.
Kab NAHI use karein / iski keemat: container ek indirection hai, aur indirection ki asli keemat hai. Wiring ki galtiyan compile time se hat kar startup time par chali jaati hain, stack trace gehre ho jaate hain, aur naye bande ko wiring padhne se pehle framework seekhna padta hai. Ek chhoti script ke liye, ek baar ke tool ke liye, ya aisi class ke liye jiski ek hi dependency hai jo kabhi badlegi nahi — saada new behtar engineering hai. Spring manzil nahi hai; swappability aur testability manzil hai. Demo ki line C dekhiye: constructor-injected class ko haath se, lambda ko fake bana kar, bina kisi container ke banaya ja sakta hai. Yahi asli faayda hai, aur ye project me Spring ho ya na ho, milta hai.
interface MessageSender { String send(String msg); }
class EmailSender implements MessageSender { public String send(String m){ return "EMAIL: " + m; } }
class SmsSender implements MessageSender { public String send(String m){ return "SMS: " + m; } }
// BEFORE: OrderService decides for itself who its collaborator will be.
class TightlyCoupledOrderService {
private final MessageSender sender = new EmailSender(); // <-- the problem
String placeOrder(String item){ return sender.send("Order placed: " + item); }
}
// AFTER: OrderService only asks. Who supplies it is not its problem.
class OrderService {
private final MessageSender sender;
OrderService(MessageSender sender){ this.sender = sender; }
String placeOrder(String item){ return sender.send("Order placed: " + item); }
}
@Configuration
class AppConfig {
@Bean MessageSender messageSender(){ return new SmsSender(); }
@Bean OrderService orderService(MessageSender s){ return new OrderService(s); }
}
public class T01 {
public static void main(String[] a){
System.out.println("A tight-coupled : " + new TightlyCoupledOrderService().placeOrder("Laptop"));
System.out.println(" to switch to SMS you must edit OrderService itself");
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
OrderService svc = ctx.getBean(OrderService.class);
System.out.println("B container-wired: " + svc.placeOrder("Laptop"));
System.out.println(" OrderService was never opened - only the config changed");
}
OrderService unitTestable = new OrderService(m -> "FAKE: " + m);
System.out.println("C no container : " + unitTestable.placeOrder("Laptop"));
}
}Dependency injection: constructor vs setter vs field
Spring aapke object ko dependency teen jagah se de sakta hai: constructor se, setter se, ya seedha field me reflection se. Teenon chalte hain. Sirf ek hi sahi default hai, aur interview me sawaal hamesha kyun ka hota hai.
Constructor injection dependency ko constructor parameter ki tarah leta hai. Isse turant do baatein nikalti hain, aur dono dikhawe ki nahi hain. Pehli, field final ban sakta hai — object jis pal banta hai poora bana hota hai, baad me aadha-adhoora ho hi nahi sakta. Doosri, dependency constructor ke signature me dikhti hai, isliye class imaandaar rehti hai: chhe parameter wala constructor matlab chhe kaam karti class, aur ye aapko body khole bina dikh jaata hai. Ye dikhna ek khoobi hai. Field injection wahi chhe dependencies chhupa deta hai aur class chupchaap badhti rehti hai.
Setter injection ise setter se leta hai, jab no-argument constructor pehle hi chal chuka hota hai. Yaani ek window aati hai jisme object maujood hai par uska collaborator abhi null hai. Yahi iski keemat hai, aur yahi iske hone ki wajah bhi: jab dependency sach me optional ho, ya baad me badalni ho, tab yahi sahi auzaar hai.
Field injection — @Autowired seedha private field par — likhne me sabse chhota aur bachne layak. Spring ise reflection se set karta hai, private ko lang kar aur bina kisi setter ke. Teen cheezein tootti hain. Field final nahi ban sakta. Dependency kisi signature me nahi dikhti, isliye class ko das dependencies jama karne se koi nahi rokta. Aur class bina container ke untestable ho jaati hai: new FieldInjected() khushi-khushi compile hota hai aur use karte hi NullPointerException deta hai — neeche run ki line B yahi dikha rahi hai.
Yahi aakhri baat logon ko manaati hai. Demo dhyaan se dekhiye ki wo sabit kya karta hai: container ke andar teenon bilkul ek jaise chalte hain — wahi log line, koi farq nahi. Farq tabhi dikhta hai jab object ko container se bahar nikaala jaaye — aur unit test bilkul yahi karta hai. Field injection tab tak muft lagta hai jab tak aap use test karne nahi jaate.
Kaun sa kab use karein: har mandatory dependency ke liye constructor injection — aur lagbhag saari mandatory hi hoti hain. Sach me optional ya runtime par badalne wali dependency ke liye setter injection. Production code me field injection: lagbhag kabhi nahi — uski ek hi jaayaz jagah hai, koi throwaway test fixture ya sample code jahan chhota likhna sab par bhaari pade.
Ek suvidha jaan lena zaroori hai kyunki har modern codebase me dikhti hai: agar class me theek ek constructor hai, to us par @Autowired likhna optional hai. Spring wahi constructor apne aap use kar leta hai. Isi wajah se bahut saare asli Spring code me kahin @Autowired nahi dikhta aur log galti se samajh lete hain ki DI ho hi nahi raha — ho raha hai, ekmatr maujood constructor se.
Kab NAHI / constructor injection ki imaandaar had: yahi wajah hai ki do beans ke beech circular dependency startup par saaf fail ho jaati hai, jabki field injection use chupchaap sulja deta. Ye constructor injection ka kharaab hona nahi hai — ye cycle ka ek asli design masla hona hai jise constructor injection chhupane se mana kar deta hai. circular-dependency-problem topic bilkul yahi experiment chala kar dikhata hai. Aur haan, bahut saare parameter wala constructor shor lagta hai; iska sahi jawab ye hai ki us shor ko signal maan kar class todi jaaye, na ki use chup karaane ke liye field injection par shift kiya jaaye.
interface AuditLog { void write(String s); }
class ConsoleAudit implements AuditLog { public void write(String s){ System.out.println(" audit> " + s); } }
class ConstructorInjected {
private final AuditLog log; // can be final
ConstructorInjected(AuditLog log){ this.log = log; }
void use(){ log.write("constructor-injected ran"); }
}
class SetterInjected {
private AuditLog log; // cannot be final
@Autowired void setLog(AuditLog log){ this.log = log; }
void use(){ log.write("setter-injected ran"); }
}
class FieldInjected {
@Autowired private AuditLog log; // not final, not in any signature
void use(){ log.write("field-injected ran"); }
}
@Configuration class Cfg {
@Bean AuditLog auditLog(){ return new ConsoleAudit(); }
@Bean ConstructorInjected c(AuditLog l){ return new ConstructorInjected(l); }
@Bean SetterInjected s(){ return new SetterInjected(); }
@Bean FieldInjected f(){ return new FieldInjected(); }
}
public class T02 {
public static void main(String[] a){
try (var ctx = new AnnotationConfigApplicationContext(Cfg.class)) {
System.out.println("A inside the container all three work identically:");
ctx.getBean(ConstructorInjected.class).use();
ctx.getBean(SetterInjected.class).use();
ctx.getBean(FieldInjected.class).use();
}
System.out.println("B now WITHOUT the container, the way a unit test builds them:");
new ConstructorInjected(s -> System.out.println(" fake> " + s)).use();
try {
new FieldInjected().use();
} catch (Exception e) {
System.out.println(" field-injected: " + e.getClass().getSimpleName()
+ " - outside the container this object is born incomplete");
}
}
}Project: Configurable Notification Service
Ye chapter ka entry project hai, aur jaan-boojh kar chhota hai: ek service jo notifications bhejti hai, aur teen alag mechanisms se teen tarah wire hoti hai — jinhe aap alag-alag pehle mil chuke hain. Maqsad ye dekhna hai ki topics 2, 7 aur 11 ek hi object graph par ek saath kaam kar rahe hain, kyunki asli Spring code aisa hi dikhta hai — in features me se ek ko akele use karna kam hi hota hai.
Samasya. NotificationService ko ek message bhejna hai. Development me console par chhapna chahiye; production me SMS se jaana chahiye. Aur use ye bhi kar paana chahiye ki maujooda environment ke har channel par broadcast kar de. Aur service use karne wale kisi bande ko in me se kuch bhi jaanne ki zaroorat nahi honi chahiye.
Teenon vichaar kaise judte hain.
@Profile tay karta hai ki kaun se channels hain hi. ConsoleChannel aur EmailChannel par @Profile("!prod") hai, isliye production me wo maujood hi nahi hain. SmsChannel par @Profile("prod") hai aur wo sirf wahin hai. Dhyaan dijiye ye ek na-hone ki tarah kaha gaya hai, kisi shart ki tarah nahi — service me kahin koi if nahi hai jo poochhe ki environment kaun sa hai.
@Primary tay karta hai ki jab ek channel maanga jaaye to kaun jeetega. Har profile ka apna @Primary bean hai: development me ConsoleChannel, production me SmsChannel. Isliye NotificationService ek saada NotificationChannel parameter le sakti hai aur jahan bhi chal rahi ho wahan ka sahi default use hamesha mil jaata hai.
List ke saath constructor injection service ko doosri kshamta deta hai. List<NotificationChannel> all ko maujooda profile ka har active channel milta hai, aur broadcast usi par ghoomta hai. Output dekhiye: dev-jaise run me list me do entry hain (console aur email); prod me ek (sms). Wahi code, wahi method, alag content — poora faisla wiring ka.
Run ko dhyaan se padhiye, kyunki ek line hi poora sabak deti hai. Run A me broadcast list [console, email] hai, aur run B me [sms]. NotificationService me kuch nahi badla. Uske andar na koi configuration flag hai, na environment ki jaanch, na koi branch. Service ne "default channel" aur "saare channels" maange, aur container ne dono environments me alag jawab diya.
Ye shakl copy karne layak kyun hai. Ab WhatsApp support jodna matlab hai: ek WhatsAppChannel class likhiye, us par @Component aur sahi @Profile lagaiye, aur ruk jaaiye. NotificationService kholi nahi jaati, koi configuration edit nahi hoti, aur broadcast use apne aap utha leta hai kyunki list injection ka matlab hi yahi hai. Yahi wo faayda hai jiska why-spring ne waada kiya tha, yahan thos shakl me.
Do baatein jinka chhoot jaana aasaan hai. Pehli, primary aur all dono ek hi constructor se inject hote hain — ek ek bean maangta hai aur doosra us type ka poora collection, aur Spring dono ko bina kisi ishaare ke alag tareeqe se resolve karta hai. Doosri, @Primary sirf single-value injection par asar daalta hai; List ko har match milta hai chahe kuch bhi ho — bilkul wahi behaviour jo autowiring-and-qualifier ne dikhaya tha.
Neeche ka code padhne se pehle ise khud banaiye. Interface aur do implementations se shuru kijiye, sirf single-channel injection ke saath service compile karwaiye, aur uske baad hi List jodiye. Profiles sabse aakhir me jodiye — ek baar bina profile aur ek baar prod ke saath chalana hi mechanism ko saaf kar deta hai.
interface NotificationChannel { String deliver(String to, String body); }
@Component("emailChannel") @Profile("!prod")
class EmailChannel implements NotificationChannel {
public String deliver(String to, String body){ return "[email -> " + to + "] " + body; }
}
@Component("smsChannel") @Profile("prod") @Primary
class SmsChannel implements NotificationChannel {
public String deliver(String to, String body){ return "[sms -> " + to + "] " + body; }
}
@Component("consoleChannel") @Profile("!prod") @Primary
class ConsoleChannel implements NotificationChannel {
public String deliver(String to, String body){ return "[console -> " + to + "] " + body; }
}
@Service
class NotificationService {
private final NotificationChannel primary; // whatever @Primary says for this profile
private final List<NotificationChannel> all; // every channel active in this profile
NotificationService(NotificationChannel primary, List<NotificationChannel> all) {
this.primary = primary;
this.all = all;
}
String notifyOne(String to, String body){ return primary.deliver(to, body); }
List<String> broadcast(String to, String body){
List<String> out = new ArrayList<>();
for (NotificationChannel c : all) out.add(c.deliver(to, body));
return out;
}
}
@Configuration @ComponentScan(basePackageClasses = P16.class) class Cfg {}
public class P16 {
static void boot(String label, String... profiles){
var ctx = new AnnotationConfigApplicationContext();
if (profiles.length > 0) ctx.getEnvironment().setActiveProfiles(profiles);
ctx.register(Cfg.class);
ctx.refresh();
NotificationService svc = ctx.getBean(NotificationService.class);
System.out.println(label);
System.out.println(" notifyOne -> " + svc.notifyOne("waquar@example.com", "Your order shipped"));
System.out.println(" broadcast -> " + svc.broadcast("waquar@example.com", "Your order shipped"));
ctx.close();
}
public static void main(String[] a){
boot("A no profile (dev-like):");
boot("B active = prod :", "prod");
}
}Spring Core & Dependency Injectioninterview questions & answers
10 sample questions below — 205+ in the full bank inside.
Ek @Bean method other() par @Bean(name = "utcClock") likha hai. Bean ka naam kya hoga?
utcClock. Saaf likha naam method ke naam ko poori tarah hata deta hai, isliye containsBean("other") ab false hai — method ka naam alias ki tarah bacha nahi rehta. Ye maan lene ki jagah jaanchne layak hai, kyunki iska matlab hai ki maujooda @Bean method par naam likh dena us har cheez ko chupchaap tod deta hai jo purane, method wale naam se ishara kar rahi thi.
In simple terms: Jaal ye maan lena hai ki method ka naam ek extra naam ki tarah bacha rahega. Ye jaanna ki nahi bachta, wahi detail hai jo tabhi aati hai jab aapne containsBean ka output sach me dekha ho, annotation dekh kar andaza na lagaya ho.
Kya aaj ke zamaane me XML configuration jaanna zaroori hai?
Use pehchaan lena aana chahiye, usme naya code likhna nahi. <bean id="..." class="..."/> element bilkul wahi metadata likhta hai jo @Bean method ya @Component likhta hai — concept wahi, syntax purana. Interviewers aaj bhi poochhte hain ki aapne XML config dekhi hai ya nahi, kyunki bahut se purane systems isi par chal rahe hain aur unhe koi to sambhaalta hai. Use padh lena asli hunar hai; naye project ke liye use chunna nahi.
In simple terms: Yahan imaandaar rukh maayne rakhta hai. XML ko poori tarah nakaar dena purane systems ka tajurba na hone jaisa lagta hai, aur use aaj ka vikalp bataana peeche reh jaane jaisa; sahi rukh hai — pehchaaniye, likhiye mat.
@Primary kya karta hai?
Wo ek bean ko us type ka default jawab bana deta hai. Ye bean ka gun hai: ek baar likh dijiye aur us type ka har bina-qualifier wala injection point wahi bean paayega. Do Sender beans hon aur SMS wali @Primary ho, to saada Sender parameter SMS wali bean paata hai. Ye default hai, sakht hukum nahi — wo tabhi faisla karta hai jab injection point par kisi ne kuch aur na kaha ho.
In simple terms: Pakadne layak baat ye hai ki @Primary bean ka gun hai jabki qualifier injection point ka gun hai. Yahi farq precedence wale sawaal ko ratne ki jagah samajh kar jawab dene layak banata hai.
Bean definition register hone ke kaun se raaste hain?
Java configuration — @Configuration aur @Bean, jahan method khud recipe hai. Component scanning, jahan Spring @Component wali class dhoondh kar usse definition nikaal leta hai. Programmatic registration, jahan aap khud BeanDefinition bana kar register karte hain. Aur XML, sabse purana tareeqa, jahan <bean id="..." class="..."/> element wahi metadata likhta hai. Chaaron ek hi cheez likhte hain — metadata — bas syntax alag hai.
In simple terms: Jawab ko jodne wali baat aakhri hai: ye chaar alag mechanism nahi hain, ek hi metadata likhne ke chaar tareeqe hain, aur definitions register hone ke baad container ko koi farq dikhta hi nahi.
Constructor injection ke saath circular dependency poori kyun nahi ho sakti?
Kyunki koi aisa kram hai hi nahi jo chale. A ko banne ke liye B chahiye aur B ko banne ke liye A, isliye Spring jisse bhi shuru kare, uske liye doosra pehle se maujood hona chahiye. Beech ka koi raasta hai nahi: constructor injection ka matlab hai ki collaborator haath me hona chahiye isse pehle ki object bane hi. Container ise pakad leta hai aur chakkar kaatne ki jagah startup par fail ho jaata hai.
In simple terms: Ise framework ki kami nahi balki kram ka namumkin hona bataana hi field injection wali aage ki asamaanta ko samajhne layak banata hai. Construction ke waqt ye cycle sach me poori ho hi nahi sakti.
Component scan se milne wali class ka bean naam kya hota hai?
Class ka naam chhote pehle akshar ke saath, yaani ScannedBean se scannedBean. Usool wahi hai jo @Bean methods ka hai — jo identifier aapne chuna nahi wo aapke likhe code se nikal aata hai — aur nateeja bhi wahi hai: class ka naam badla to bean ka naam badla, aur purane naam par ishara karti koi bhi qualifier string startup par toot jaati hai, bina compile error ke.
In simple terms: Naam ka rule apne aap me mamooli jaankaari hai; use rename wale nateeje se jodna hi jawab ko kaam ka banata hai. Dhyaan dijiye ki pattern dono mechanism me ek hi hai, aur ye kehne layak hai kyunki isse ek hi rule dono ko dhak leta hai.
AOP kis masle ke liye bana hai?
Un cheezon ke liye jo ek jagah rehne se inkaar kar deti hain. Logging, timing, security ki jaanch aur transaction ki seemayein — har ek apne aap me ek soch hai, aur har ek sau methods ke shuru aur aakhir me copy-paste ho jaati hai. Yahi cross-cutting concerns hain, aur aspect-oriented programming inhe ek baar kehne ke liye hai. Koi cheez isme aati hai ya nahi, iski jaanch ye hai ki wo logic bahut se methods me bilkul ek jaisa hai aur un methods ke apne kaam se alag hai.
In simple terms: Jaanch par khatm karna hi jawab ko istemal layak banata hai, kyunki AOP ki kharaabi tab hoti hai jab use aise logic par lagaya jaaye jo sach me ek jaisa hai hi nahi. Chaar aam misaalein batana umeed ke mutabik hai, par samajh jaanch se dikhti hai.
@Autowired kaise tay karta hai ki kaun si bean inject karni hai?
Pehle type se. Spring parameter ya field ke declare kiye type ko apni beans se milaata hai, aur naam par tabhi aata hai jab akele type se do-matlab ban jaaye. Yahi do-qadam wala rule poora mechanism hai, aur isi se samajh aata hai ki interview ke lagbhag saare autowiring sawaal asal me is baat ke sawaal hain ki type ek se zyada baar match ho jaaye to kya hota hai.
In simple terms: Pehle type, naam sirf barabari todne ke liye — yahi line taiyaar rakhni chahiye. Jo log kehte hain ki Spring naam se milaata hai unka model ulta hai, aur phir har ambiguity wala sawaal zaroorat se zyada mushkil ho jaata hai.
@Qualifier ambiguity kaise hataata hai?
Wo injection point par us bean ka naam le leta hai jo aapko chahiye. Jahan @Primary ek baar bean par likha jaata hai, wahan @Qualifier("email") wahan likha jaata hai jahan dependency istemal ho rahi hai, isliye chunav wahin, saaf-saaf hota hai — consumer padhte hi pata chal jaata hai ki kya aayega. Yahi saaf hona uska sabse bada faayda bhi hai aur sabse badi keemat bhi, kyunki naam ek string hai jise compiler jaanchta hi nahi.
In simple terms: Jagah bata kar jawab dena — bean par nahi, injection point par — hi @Primary se tulna ko matlab deta hai. Isse bina-jaanchi string wale trade-off tak baat apne aap pahunch jaati hai.
Jab bean ke paas constructor hai hi, to lifecycle callbacks ki zaroorat kyun?
Kyunki constructor hamesha kaam poora nahi kar sakta. Bean ko dependencies aane ke baad kuch karna pad sakta hai — connection kholna, cache garam karna, ye jaanchna ki jo configuration mili hai uska koi matlab bhi hai — aur application band hote waqt use jo khola tha wo chhodna pad sakta hai. Ye do lamhe hi in callbacks ke liye hain. Neeche ki asli baat ye hai ki initialisation callback chalne tak dependency injection ho chuka hota hai, jis par setter ya field injection wale bean ka constructor bharosa nahi kar sakta.
In simple terms: Jawab ko is baat par tikana ki dependencies kab maujood hoti hain, baaki poore topic ko usi se nikalta hai. Isse wo imaandaar baat bhi banti hai ki constructor injection initialisation hook ki zaroorat kaafi had tak khatam kar deta hai.
195+ more Spring Core & Dependency Injection questions inside
Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.
Unlock all questions — freeReady to practise Spring Core & Dependency Injection?
Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.