Dependency injection trong Spring: @Autowired, @Qualifier và @Primary

- Published on
- 14 mins read
App vừa khởi động đã dừng với NoUniqueBeanDefinitionException: có hai bean cùng implement một interface, và Spring không biết chọn cái nào. Ở một góc khác của codebase, unit test cho OrderService phải dựng cả Spring Context chỉ vì mọi dependency đều được @Autowired thẳng vào field.
Cả hai đều xoay quanh một câu hỏi: Spring chọn bean nào, và đưa nó vào class của bạn bằng đường nào.
# giới thiệu
Dependency Injection (DI) là pattern mà class không tự tạo dependency bên trong, mà nhận từ bên ngoài vào. Nghe thì đơn giản, nhưng nó đổi hẳn cách bạn viết và test code.
Không có DI thì OrderService tự new OrderRepository(): dính chặt (tight coupling), không mock được, muốn đổi implementation cũng không được. Có DI thì Spring "tiêm" repository vào service, các class tách rời nhau, dễ test, dễ cấu hình.
Package org.springframework.beans.factory.annotation chứa mấy annotation quyết định Spring inject thế nào: inject cái gì (@Autowired), chọn bean nào (@Qualifier, @Primary), lấy config ở đâu (@Value). Dev Spring nào cũng đụng tới chúng hằng ngày.
# @Autowired: tự động inject dependency
@Autowired bảo Spring: "Tìm bean hợp trong container rồi inject vào đây." Spring so theo type trước, có nhiều bean trùng type thì mới xét tới tên biến hoặc qualifier.
Spring hỗ trợ 3 đường inject là qua constructor, qua field và qua setter. Tuy nhiên với code chạy production, bạn gần như chỉ nên dùng constructor injection. Lý do rất thực tế: các field phụ thuộc đều khai báo được là final (bất biến và an toàn khi chạy đa luồng), nhìn vào chữ ký hàm khởi tạo là biết ngay class này cần những gì (nếu một constructor đòi tới 8–10 tham số thì đó là tín hiệu rõ ràng class đang ôm quá nhiều việc, vi phạm Single Responsibility).
Quan trọng hơn cả là cơ chế fail-fast: thiếu bean là ứng dụng báo lỗi UnsatisfiedDependencyException ngay lúc khởi động chứ không đợi tới lúc khách bấm nút mới văng NullPointerException. Còn khi viết unit test thì bạn cứ new OrderService(mockRepo, ...) thuần Java mà không cần dựng cả Spring Context nặng nề, quên truyền dependency nào là compiler báo luôn.
Kết hợp thêm Lombok @RequiredArgsConstructor thì code vừa gọn như field injection mà vẫn giữ nguyên mọi lợi điểm của constructor injection, vì Lombok tự sinh constructor cho toàn bộ các field final lúc biên dịch.
# constructor injection (recommended)
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final ProductService productService;
private final NotificationService notificationService;
// @Autowired không cần khi chỉ có 1 constructor (Spring Framework 4.3+)
public OrderService(OrderRepository orderRepository,
ProductService productService,
NotificationService notificationService) {
this.orderRepository = orderRepository;
this.productService = productService;
this.notificationService = notificationService;
}
}
// Lombok equivalent (cách nên dùng)
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final ProductService productService;
private final NotificationService notificationService;
}# field injection (nên tránh, khó test)
Gắn @Autowired thẳng lên biến private nhìn thì ngắn gọn nhưng buộc Spring phải dùng reflection để gán giá trị sau khi đã gọi constructor rỗng. Vì không có constructor nhận tham số nên bạn không thể đánh dấu field là final, và khi viết unit test độc lập không có Spring thì phải dùng ReflectionTestUtils hoặc @InjectMocks của Mockito mới nhét được mock vào:
@Service
public class OrderService {
@Autowired // Inject trực tiếp vào field
private OrderRepository orderRepository;
@Autowired(required = false) // Optional — null nếu bean không tồn tại
private CacheService cacheService;
}# setter injection (optional dependencies)
Setter injection dành cho những phụ thuộc không bắt buộc (optional) hoặc có nhu cầu đổi lại tham chiếu ở thời điểm runtime. Với required = false như dưới, class vẫn khởi tạo được bình thường ngay cả khi không có bean tương ứng trong container:
@Service
public class OrderService {
private NotificationService notificationService;
@Autowired(required = false)
public void setNotificationService(NotificationService notificationService) {
this.notificationService = notificationService;
}
public void createOrder(OrderRequest request) {
// ... create order
if (notificationService != null) {
notificationService.notify(order);
}
}
}# collection injection
Một tính năng rất tiện của Spring mà người mới đôi khi bỏ sót là inject cả một tập hợp (List<T>, Set<T>) hoặc bảng ánh xạ (Map<String, T>). Khi thấy kiểu tham số là List<NotificationSender>, Spring không đi tìm một bean tên là List, mà tự động gom tất cả các bean đang implement interface NotificationSender trong container lại thành một danh sách (có thể sắp thứ tự bằng @Order):
@Service
public class NotificationDispatcher {
// Inject TẤT CẢ beans implement NotificationSender
private final List<NotificationSender> senders;
@Autowired
public NotificationDispatcher(List<NotificationSender> senders) {
this.senders = senders;
// senders = [EmailSender, SmsSender, PushSender] (tất cả impl)
}
public void dispatch(Notification notification) {
senders.forEach(sender -> sender.send(notification));
}
}
// Map injection — key = bean name (mặc định là tên class viết thường chữ đầu)
@Autowired
private Map<String, PaymentProcessor> processors;
// processors = {"stripeProcessor": StripeProcessor, "vnPayProcessor": VnPayProcessor}# @Qualifier: chọn đúng bean khi có nhiều ứng viên
Container có nhiều bean cùng type (2 DataSource, 3 PaymentProcessor...) thì Spring không biết inject cái nào → NoUniqueBeanDefinitionException. @Qualifier gỡ chuyện này bằng cách chỉ đích danh tên bean.
Ví dụ hay gặp nhất là primary database (write) với replica database (read). Service đọc nhiều thì dùng replica, service cần ghi thì dùng primary. Cùng là type DataSource, nhưng nhờ @Qualifier mà inject đúng instance.
Xịn hơn chút thì tự tạo qualifier annotation (@PrimaryDatabase, @ReplicaDatabase): dễ đọc hơn qualifier dạng string, lại được compiler bắt lỗi gõ sai.
// Nhiều beans cùng type
@Configuration
public class DataSourceConfig {
@Bean("primaryDs")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().url("jdbc:postgresql://primary:5432/db").build();
}
@Bean("replicaDs")
public DataSource replicaDataSource() {
return DataSourceBuilder.create().url("jdbc:postgresql://replica:5432/db").build();
}
}
// Inject với @Qualifier
// ⚠️ Lombok mặc định KHÔNG chép @Qualifier từ field sang tham số constructor.
// Cần thêm vào lombok.config:
// lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
@Service
@RequiredArgsConstructor
public class ReportService {
@Qualifier("replicaDs") // Chọn replica cho read-heavy operations
private final DataSource dataSource;
}
// Hoặc với constructor
@Service
public class ReportService {
private final DataSource readDataSource;
public ReportService(@Qualifier("replicaDs") DataSource readDataSource) {
this.readDataSource = readDataSource;
}
}# custom qualifier annotation
// Tạo custom qualifier
// METHOD là bắt buộc để gắn được lên method @Bean bên dưới
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface PrimaryDatabase {}
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface ReplicaDatabase {}
// Đánh dấu beans
@Bean
@PrimaryDatabase
public DataSource primaryDs() { ... }
@Bean
@ReplicaDatabase
public DataSource replicaDs() { ... }
// Inject
@Service
public class OrderService {
public OrderService(@PrimaryDatabase DataSource ds) { ... }
}
@Service
public class ReportService {
public ReportService(@ReplicaDatabase DataSource ds) { ... }
}# @Value: inject giá trị property
@Value là cách nhanh nhất để đưa giá trị config vào code. Đi kèm Spring Cloud Config Server thì config được quản lý tập trung một chỗ. Có điều @Value chỉ được inject một lần lúc bean khởi tạo: đổi config trên server thì app vẫn giữ giá trị cũ cho tới khi restart, trừ khi bean được đánh dấu @RefreshScope và bạn gọi /actuator/refresh (hoặc dùng Spring Cloud Bus). Config nhiều trường liên quan nhau thì @ConfigurationProperties gọn và an toàn kiểu hơn là rải @Value khắp nơi.
Cú pháp ${property.name:defaultValue}: phần sau dấu : là giá trị dự phòng khi property không có. Config nào không bắt buộc thì nhớ đặt default value, kẻo app start không lên.
Dùng SpEL (Spring Expression Language) trong @Value thì làm được nhiều hơn là inject string: gọi method, tính toán, đọc system properties. Nhưng đừng lạm dụng, logic phức tạp thì để trong code, đừng nhét vào annotation.
@Service
public class FileService {
@Value("${app.upload.max-size:10485760}")
private long maxFileSize;
@Value("${app.upload.path}")
private String uploadPath;
@Value("${app.upload.allowed-types:pdf,png,jpg}")
private List<String> allowedTypes;
@Value("#{${app.feature-flags:{:}}}") // SpEL → Map (trong SpEL, {:} là map rỗng, còn {} là LIST rỗng)
private Map<String, Boolean> featureFlags;
@Value("${app.name:#{null}}") // null default
private String appName;
// SpEL expressions
@Value("#{systemEnvironment['JAVA_HOME']}")
private String javaHome;
@Value("#{T(java.time.LocalDate).now()}")
private LocalDate today;
@Value("#{@someBean.computeValue()}") // Call another bean's method
private String computedValue;
// Hoặc constructor injection with @Value (chọn MỘT trong hai cách, đừng khai báo cả field lẫn constructor như minh hoạ này)
public FileService(
@Value("${app.upload.max-size:10485760}") long maxFileSize,
@Value("${app.upload.path}") String uploadPath) {
this.maxFileSize = maxFileSize;
this.uploadPath = uploadPath;
}
}# @Lookup: method injection cho prototype bean
Cái này dành cho một tình huống ít người để ý: singleton bean cần một prototype bean mới tinh mỗi lần gọi.
Inject prototype vào singleton qua constructor thì prototype chỉ được tạo đúng 1 lần (lúc singleton khởi tạo), coi như mất luôn ý nghĩa prototype. Với @Lookup, Spring override method đó để mỗi lần gọi là trả về một instance mới.
Ngoài đời không gặp nhiều, nhưng có ích khi làm report builder cần giữ state, xử lý theo từng request trong singleton service, hay mấy object kiểu command pattern.
// Problem: Singleton service cần mỗi lần 1 prototype bean mới
@Service
public abstract class ReportService {
// Spring override method này → trả về new prototype instance mỗi lần gọi
@Lookup
protected abstract ReportGenerator createGenerator();
public String generateReport(ReportRequest request) {
ReportGenerator generator = createGenerator(); // New instance mỗi lần
generator.addHeader(request.getTitle());
generator.addData(request.getData());
return generator.generate();
}
}
@Component
@Scope("prototype")
public class ReportGenerator {
private final StringBuilder content = new StringBuilder();
public void addHeader(String title) { content.append("# ").append(title).append("\n"); }
public void addData(Object data) { content.append(data.toString()); }
public String generate() { return content.toString(); }
}# @Primary: bean mặc định khi có nhiều ứng viên
@Primary là kiểu "mặc định mềm": không ghi @Qualifier thì Spring lấy bean có @Primary. Còn khi cần bean khác thì @Qualifier luôn thắng @Primary.
Cách dùng hay gặp: Redis cache để @Primary (dùng mặc định), local cache làm phương án phụ (cho test hoặc fallback). Hoặc DataSource production để @Primary, còn DataSource test thì gọi bằng @Qualifier("testDb").
@Configuration
public class CacheConfig {
@Bean
@Primary // Default khi inject CacheManager không chỉ định @Qualifier
public CacheManager redisCacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.builder(factory).build();
}
@Bean("localCache")
public CacheManager localCacheManager() {
return new ConcurrentMapCacheManager("products", "users");
}
}
// Inject — không cần @Qualifier, tự động chọn @Primary
@Service
@RequiredArgsConstructor
public class ProductService {
private final CacheManager cacheManager; // → redisCacheManager
}
// Override khi cần
@Service
public class TestService {
public TestService(@Qualifier("localCache") CacheManager cache) { ... }
}# @Required (deprecated) & alternatives
@Required hồi trước gắn lên setter để báo "property này bắt buộc phải inject". Từ Spring 5.1 nó bị deprecated, và tới Spring Framework 6.0 thì bị xoá hẳn (trong spring-beans 6.x không còn class này), vì constructor injection làm việc này gọn hơn: thiếu dependency là app không start được.
Nhìn lại mới thấy: khi bạn dùng constructor injection làm mặc định, bản thân ngôn ngữ Java đã tự ép phải truyền đủ phụ thuộc rồi, nên mấy annotation kiểm tra kiểu @Required tự khắc trở nên dư thừa.
// @Required deprecated từ Spring 5.1, bị xoá ở Spring 6.0 — dùng constructor injection thay thế
// ❌ Old way
@Component
public class OldService {
private Repository repo;
@Required // Deprecated (5.1), không còn ở Spring 6+
public void setRepo(Repository repo) { this.repo = repo; }
}
// ✅ Modern way — constructor injection (required by default)
@Service
@RequiredArgsConstructor
public class ModernService {
private final Repository repo; // Bắt buộc phải inject
}# objectprovider & lazy resolution
ObjectProvider<T> là phiên bản hiện đại và an toàn hơn nhiều so với @Autowired(required = false) khi bạn cần làm việc với những bean có thể không tồn tại hoặc chưa muốn khởi tạo ngay. Thay vì để lại một biến null chực chờ gây NullPointerException, ObjectProvider đóng vai trò một cánh cổng truy vấn lười (lazy lookup) vào container với bộ hàm rõ ràng như getIfAvailable(), getIfUnique() hay orderedStream(). Cách này đặc biệt phát huy tác dụng khi làm kiến trúc plugin (quét và gọi động mọi bản cài đặt hiện có theo thứ tự @Order), bật tắt tính năng tuỳ chọn theo môi trường mà không làm gãy service chính, hoặc trì hoãn việc khởi tạo những bean nặng/phá vòng lặp phụ thuộc (circular dependency):
@Service
public class FlexibleService {
private final ObjectProvider<ExpensiveService> expensiveServiceProvider;
private final ObjectProvider<List<Plugin>> pluginsProvider;
@Autowired
public FlexibleService(
ObjectProvider<ExpensiveService> expensiveServiceProvider,
ObjectProvider<List<Plugin>> pluginsProvider) {
this.expensiveServiceProvider = expensiveServiceProvider;
this.pluginsProvider = pluginsProvider;
}
public void doWork() {
// Lazy resolution — chỉ tạo khi cần
ExpensiveService service = expensiveServiceProvider.getIfAvailable();
if (service != null) {
service.process();
}
// Với default fallback
ExpensiveService serviceOrDefault = expensiveServiceProvider
.getIfAvailable(NoOpExpensiveService::new);
// Stream tất cả beans
expensiveServiceProvider.stream().forEach(s -> s.process());
// Ordered
expensiveServiceProvider.orderedStream().forEach(s -> s.process());
}
}# injection patterns: vài cách dùng hay
Khi kết hợp khéo các cơ chế trên, DI vượt ra khỏi chuyện "tiêm biến" đơn thuần để trở thành công cụ thiết kế cách các component phối hợp với nhau mà không cần sửa code cũ (đúng tinh thần Open/Closed Principle).
Strategy Pattern qua DI là ví dụ quen thuộc: khai báo interface, viết nhiều implementation, inject List<Interface> → runtime tự chọn. Không cần factory class, không cần switch/case, Spring gom hết implementation cho bạn.
# pattern 1: strategy pattern via di
public interface PaymentProcessor {
boolean supports(PaymentMethod method);
PaymentResult process(PaymentRequest request);
}
@Component
public class StripeProcessor implements PaymentProcessor {
public boolean supports(PaymentMethod m) { return m == PaymentMethod.CREDIT_CARD; }
public PaymentResult process(PaymentRequest req) { ... }
}
@Component
public class VnPayProcessor implements PaymentProcessor {
public boolean supports(PaymentMethod m) { return m == PaymentMethod.BANK_TRANSFER; }
public PaymentResult process(PaymentRequest req) { ... }
}
@Service
@RequiredArgsConstructor
public class PaymentService {
private final List<PaymentProcessor> processors; // Auto-inject all implementations
public PaymentResult pay(PaymentRequest request) {
return processors.stream()
.filter(p -> p.supports(request.getMethod()))
.findFirst()
.orElseThrow(() -> new UnsupportedPaymentException(request.getMethod()))
.process(request);
}
}# pattern 2: conditional dependencies
@Service
public class NotificationService {
private final Optional<SmsGateway> smsGateway; // May not exist
private final Optional<PushService> pushService; // May not exist
private final EmailService emailService; // Always exists
public NotificationService(
EmailService emailService,
Optional<SmsGateway> smsGateway,
Optional<PushService> pushService) {
this.emailService = emailService;
this.smsGateway = smsGateway;
this.pushService = pushService;
}
public void notify(User user, String message) {
emailService.send(user.getEmail(), message);
smsGateway.ifPresent(gw -> gw.send(user.getPhone(), message));
pushService.ifPresent(ps -> ps.send(user.getDeviceToken(), message));
}
}# quick reference
| Annotation | Mục đích | Khi nào dùng |
|---|---|---|
| @Autowired | Auto inject dependency | Setter/field injection (prefer constructor) |
| @Qualifier | Chọn bean cụ thể | Nhiều beans cùng type |
| @Primary | Default bean | 1 bean ưu tiên hơn |
| @Value | Inject property | Config values, SpEL |
| @Lookup | Method injection | Singleton cần prototype |
| @Required | Bắt buộc inject (đã xoá ở 6) | Dùng constructor thay thế |
# so sánh injection types
| Type | Pros | Cons | Khi nào |
|---|---|---|---|
| Constructor | Immutable, testable, required deps | Verbose (Lombok fix) | DEFAULT, luôn dùng |
| Setter | Optional deps | Mutable, hidden | Optional dependencies |
| Field | Concise | Untestable, hidden, mutable | TRÁNH, chỉ cho test class |
Thử ngay trên project của bạn: tìm những field có @Autowired trong src/main, chọn một class, đổi sang constructor injection với @RequiredArgsConstructor. Nếu constructor sinh ra có 8–10 tham số thì như đã nói ở phần @Autowired, class đó đang ôm quá nhiều việc, và đó mới là thứ cần sửa tiếp theo.
Chỉ là những ghi chép cá nhân với hy vọng mang lại chút giá trị. Nếu thấy hữu ích, đừng ngại chia sẻ cho bạn bè & đồng nghiệp nhé!
Happy coding 😎 👍🏻 🚀 🔥.
On this page
- # giới thiệu
- # @Autowired: tự động inject dependency
- # constructor injection (recommended)
- # field injection (nên tránh, khó test)
- # setter injection (optional dependencies)
- # collection injection
- # @Qualifier: chọn đúng bean khi có nhiều ứng viên
- # custom qualifier annotation
- # @Value: inject giá trị property
- # @Lookup: method injection cho prototype bean
- # @Primary: bean mặc định khi có nhiều ứng viên
- # @Required (deprecated) & alternatives
- # objectprovider & lazy resolution
- # injection patterns: vài cách dùng hay
- # pattern 1: strategy pattern via di
- # pattern 2: conditional dependencies
- # quick reference
- # so sánh injection types