构造器注入是首选方案,因为它能保证依赖不可变且对象在初始化时即完成装配,彻底杜绝空指针风险。字段注入虽然代码简洁,但会隐藏真实依赖并导致测试困难,仅在处理循环依赖或遗留系统维护时才考虑使用。

如何编写支持构造器注入的不可变组件
通过定义私有 final 字段并在构造函数中赋值,可以确保 Bean 在创建后状态稳定。Spring Boot 官方推荐此方式,因为容器会自动解析参数顺序并完成装配,无需额外注解即可实现强类型检查。

package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final PaymentGateway paymentGateway;
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
public void processOrder() {
// 业务逻辑
}
}
字段注入在哪些场景下会被使用
开发者通常在使用 Spring 内部机制(如 AOP 代理)或需要处理循环依赖时选择字段注入。这种方式允许在对象实例化后延迟赋值,但牺牲了封装性,使得类之间的耦合关系变得不透明。

package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LegacyService {
@Autowired
private NotificationService notificationService;
public void sendAlert() {
notificationService.notify();
}
}
构造器注入对单元测试的具体影响是什么
构造器注入让单元测试可以直接传入 Mock 对象,无需启动 Spring 容器即可验证业务逻辑。这种解耦方式显著提升了测试执行速度,并消除了因容器配置错误导致的测试失败。











