外观
依赖注入
来源:语雀原文 | 整理日期:2026-09-22
依赖注入(Dependency Injection, DI)是软件开发中的一种设计模式,它可以使代码更加松耦合、便于测试和维护。在Java开发中,尤其是在Spring框架中,依赖注入扮演着非常重要的角色。
1. 什么是依赖注入
依赖注入是一种设计模式,其核心思想是将对象的创建和对其依赖的管理交给外部容器,而不是在内部进行管理。这促进了松耦合,使得代码更易于测试和维护。
2. 依赖注入的三种方式
- 构造器注入: 通过构造函数提供依赖对象。
- Setter方法注入: 通过Setter方法提供依赖对象。
- 字段注入: 通过属性字段提供依赖对象。
3. Spring中的依赖注入
Spring框架是Java领域最著名的依赖注入框架。它通过配置文件或注解配置来管理对象的生命周期和依赖关系。
3.1 Spring中的构造器注入
示例代码
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
class ServiceA {
// Service implementation
}
@Component
class ServiceB {
private ServiceA serviceA;
@Autowired
public ServiceB(ServiceA serviceA) {
this.serviceA = serviceA;
}
public void performTask() {
// Use serviceA to perform some task
System.out.println(this.serviceA);
}
}3.2 Spring中的Setter方法注入
示例代码
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
class ServiceA {
// Service implementation
}
@Component
class ServiceB {
private ServiceA serviceA;
@Autowired
public void setServiceA(ServiceA serviceA) {
this.serviceA = serviceA;
}
public void performTask() {
// Use serviceA to perform some task
System.out.println(this.serviceA);
}
}3.3 Spring中的字段注入
示例代码
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
class ServiceA {
// Service implementation
}
@Component
class ServiceB {
@Autowired
private ServiceA serviceA;
public void performTask() {
// Use serviceA to perform some task
System.out.println(this.serviceA);
}
}