Java Topics
HubJava Collections FrameworkCollections Practice ProgramsComparable vs ComparatorGenericsIteratorArrayListLinkedListStackVectorHashMapHashtableLinkedHashMapTreeMapArrayDequeDeque Double-Ended QueuePriorityQueueHashSetLinkedHashSetTreeSetAdapter PatternBuilder PatternFactory PatternMVC PatternObserver PatternSingleton PatternDynamic ProgrammingGraphHashingHeapLinked List DSAQueue DSARecursionSearching AlgorithmsSorting AlgorithmsStack DSATime ComplexityTreesException Handling Best PracticesCustom ExceptionException Hierarchyfinally BlockException Handlingthrow aur throwstry-catchBuffered StreamsByte StreamsCharacter StreamsDeserializationFile ClassJava NIO New I/OSerializationArrays in JavaArray OperationsArray Practice ProgramsArray Interview QuestionsJagged ArrayMulti-Dimensional ArraysOne Dimensional Arraybreak aur continuedo-while Loopfor Loopif-else StatementsNested Loopsswitch-case Statementwhile LoopJava Compilation ProcessJava ki FeaturesPehla Java ProgramHistory of JavaJava EditionsJava Program StructureJDK, JRE aur JVMJava Kya Hai?Immutable StringsString Class in JavaString Interview QuestionsString MethodsString Practice ProgramsStringBufferStringBuilderComments in JavaData Types in JavaIdentifiers in JavaInput & Output in JavaJava KeywordsOperators in JavaType Casting in JavaVariables in JavaJava Coding Interview QuestionsCollections Interview QuestionsCore Java Interview QuestionsJDBC Interview QuestionsMultithreading Interview QuestionsOOPs Interview QuestionsSpring Framework Interview QuestionsJava 8 Date/Time APIDefault aur Static Methods in InterfaceFunctional InterfaceLambda ExpressionMethod ReferenceOptional ClassStream APIBatch ProcessingCallableStatementJDBC ArchitectureJDBC — Java Database ConnectivityJDBC Practice ProjectsMySQL ConnectionPreparedStatementResultSetStatement InterfaceTransaction ManagementCreating ThreadsDaemon ThreadExecutor FrameworkInter-Thread CommunicationMultithreading Practice ProgramsRunnable InterfaceSynchronizationThread ClassMultithreading IntroductionThread Life CycleThread PriorityJava Cheat SheetImportant Formulas & Key ConceptsImportant Java ProgramsJava Quick RevisionAbstract ClassAbstractionAnonymous ClassClass and ObjectConstructorEncapsulationInheritanceInner ClassInterfaceMethod OverloadingMethod OverridingObject ClassObject CloningObject-Oriented Programming OOPPolymorphismstatic Keywordsuper Keywordthis KeywordWrapper ClassesArray Practice ProgramsBasic Java Practice ProgramsCollection Practice ProgramsJDBC Practice ProgramsMultithreading Practice ProgramsOOPs Practice ProgramsPlacement Coding QuestionsString Practice ProgramsBanking SystemChat ApplicationE-Commerce Backend — Spring Boot REST APIEmployee Management SystemLibrary Management SystemSpring Boot Fullstack ProjectStudent Management SystemCookies in ServletExpression Language ELGenericServletHttpServletJavaServer Pages JSPJSP TagsMVC ArchitectureHttpServletRequest & HttpServletResponseServlet IntroductionServlet Life CycleSession TrackingDependency InjectionSpring BeansSpring CoreSpring FrameworkAPI GatewaySpring Cloud Config ServerDocker DeploymentEureka Server — Service DiscoverySpring Boot CRUD ApplicationException Handling in Spring BootJWT AuthenticationREST API in Spring BootSpring SecuritySpring BootSpring Data JPAValidation in Spring Boot
Dependency Injection
Last Updated : 26 May, 2026
title: Dependency Injection in Spring
Spring Framework73 words6 headingsTables includedExamples included
title: Dependency Injection in Spring description: Spring DI ke types aur examples
Object apni dependencies khud create nahi karta — Spring inject karta hai.
Types
1. Constructor Injection (Recommended)
java exampleWoHoTech
@Service
public class OrderService {
private final UserRepository userRepo;
private final ProductRepository productRepo;
// @Autowired optional when single constructor
public OrderService(UserRepository userRepo, ProductRepository productRepo) {
this.userRepo = userRepo;
this.productRepo = productRepo;
}
}2. Setter Injection
java exampleWoHoTech
@Service
public class EmailService {
private MailSender mailSender;
@Autowired
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
}3. Field Injection (Simple but not recommended for testing)
java exampleWoHoTech
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
}Annotations
| Annotation | Use |
|---|---|
@Autowired | Inject dependency |
@Component | Generic bean |
@Service | Service layer |
@Repository | Data layer |
@Controller | Web controller |
@Configuration | Config class |
@Bean | Method produces a bean |
Qualifier — Multiple implementations
java exampleWoHoTech
interface PaymentGateway { void pay(double amount); }
@Component("stripe")
class StripeGateway implements PaymentGateway { ... }
@Component("paypal")
class PayPalGateway implements PaymentGateway { ... }
@Service
class CheckoutService {
@Autowired
@Qualifier("stripe")
private PaymentGateway gateway;
}Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Dependency Injection.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java topic.
Search Terms
java, java programming, core java, java master course, java notes, master, course, spring
Related Java Topics
Continue learning this concept
Spring FrameworkAPI Gatewaytitle: API Gateway - Spring Cloud GatewaySpring FrameworkSpring Cloud Config Servertitle: Config Server - Spring Cloud ConfigSpring FrameworkDocker Deploymenttitle: Docker DeploymentSpring FrameworkEureka Server — Service Discoverytitle: Eureka Server - Service DiscoverySpring FrameworkSpring Beanstitle: Spring BeansSpring FrameworkSpring Boot CRUD Applicationtitle: CRUD Application with Spring Boot