Core Annotations
@Component ek GENERIC stereotype hai — class ko Spring-managed bean banata hai. @Service, @Repository, @Controller ISI ke SPECIALIZED versions hain — semantically clear karte hain class ka ROLE (business logic, data access, web layer), aur kuch EXTRA behavior bhi dete hain (jaise @Repository exceptions ko translate karta hai).
@Autowired dependency injection trigger karta hai — Spring container se matching bean DHOOND ke inject karta hai (by type, phir by name agar multiple matches hon). @Configuration class ko mark karta hai ki usme @Bean methods hain jo Spring configuration define karते hain. @Qualifier specific bean CHOOSE karne ke liye jab multiple candidates ho.
@Repository // Data access layer
public class UserRepository { /* ... */ }
@Service // Business logic layer
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) { // @Autowired implicit hai
this.repository = repository;
}
}
@RestController // Web layer (Spring MVC)
public class UserController {
private final UserService service;
public UserController(UserService service) {
this.service = service;
}
}
@Configuration
public class AppConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}- @Component = generic, @Service/@Repository/@Controller = specialized (semantic)
- @Autowired = dependency inject karo (by type, phir by name)
- @Configuration + @Bean = Java-based configuration
Jab EK interface ke MULTIPLE implementations hon (jaise do PaymentGateway — StripeGateway aur PaypalGateway), Spring CONFUSE ho jaata hai kaun sa inject kare. @Qualifier("beanName") se SPECIFIC bean choose kar sakte ho.
@Service
public class OrderService {
private final PaymentGateway gateway;
public OrderService(@Qualifier("stripeGateway") PaymentGateway gateway) {
this.gateway = gateway; // specifically Stripe wala inject hoga
}
}@Primary ek bean ko DEFAULT CHOICE mark karta hai jab multiple candidates available hon — @Qualifier na lagाने par bhi, @Primary wali bean automatically select ho jaati hai. @Qualifier se OVERRIDE ho sakta hai specific jagah par.