java如何注入
Java依赖注入方法
依赖注入(Dependency Injection, DI)是一种设计模式,用于解耦组件间的依赖关系。Java中主要通过以下方式实现:
构造函数注入 通过构造函数传递依赖对象,适用于强依赖场景。
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Setter方法注入 通过setter方法设置依赖,适用于可选依赖。

public class OrderService {
private PaymentGateway paymentGateway;
public void setPaymentGateway(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}
字段注入 使用注解直接注入字段,代码简洁但可测试性较差。
public class ProductService {
@Autowired
private ProductRepository productRepository;
}
常用DI框架
Spring框架
使用@Autowired或@Resource注解实现自动装配:

@Service
public class CustomerService {
@Autowired
private CustomerRepository repository;
}
Google Guice
通过@Inject注解和模块配置实现:
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
}
}
手动实现DI容器
简易DI容器示例:
public class DIContainer {
private Map<Class<?>, Object> instances = new HashMap<>();
public <T> void register(Class<T> type, T instance) {
instances.put(type, instance);
}
public <T> T resolve(Class<T> type) {
return type.cast(instances.get(type));
}
}
最佳实践
- 优先使用构造函数注入,保证依赖不可变
- 避免混合使用多种注入方式
- 对可选依赖使用Setter注入
- 单元测试时考虑不使用框架的纯手工注入
以上方法可根据项目规模选择,小型项目可手动实现,企业级推荐使用Spring或Guice等成熟框架。






