目录
一、依赖注入的基本概念
依赖注入(Dependency Injection,简称DI)是Spring框架的核心功能之一,它允许将组件的依赖关系通过外部配置而非硬编码的方式进行管理。这种设计模式使得组件之间的耦合度降低,提高了代码的可测试性和可维护性。
(一)依赖注入的原理
依赖注入的核心思想是将组件的创建和依赖关系的管理交给Spring容器,而不是在组件内部直接实例化依赖对象。Spring通过反射机制,在运行时将依赖对象注入到目标组件中。
(二)依赖注入的优势
- 降低耦合度:组件不再直接依赖具体类,而是依赖接口或抽象类。
- 提高可测试性:可以轻松地为组件提供模拟依赖,便于单元测试。
- 集中管理配置:依赖关系由Spring容器统一管理,便于维护和修改。
二、依赖注入的方式
(一)构造函数注入
构造函数注入通过类的构造函数传递依赖对象,确保在对象创建时所有依赖都已就绪。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TextEditor {
private final SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.check();
}
}
(二)Setter方法注入
Setter方法注入通过提供setter方法,允许Spring在对象创建后注入依赖对象。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.check();
}
}
(三)字段注入
字段注入直接在类的字段上使用@Autowired
注解,Spring会自动注入对应的依赖对象。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TextEditor {