# Dependency Injection Object apni dependencies khud create nahi karta — Spring inject karta hai. ## Types ### 1. Constructor Injection (Recommended) ```java @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 @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 @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 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; } ```