DI VS New方式
- new 方式
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
this.spellChecker = new spellChecker();//此處緊密耦合被饿,同生共死
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}```
> TestEditor 與spellChecker緊密耦合铭若,同生共死递览。
+ DI方式
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {//此處,在采用注入的方式傳遞spellChecker對象
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg ref="spellChecker"/> <!--用ref指向依賴對象镜雨,在此處把依賴對象注入到構(gòu)造函數(shù)中儿捧,可以注入任意對象,且更改方便 -->
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
用constructor的方式注入颓影,具有很強的靈活性懒鉴,使得對象之前沒有很強的耦合性诡挂。故依賴注入的作用可以松耦合。
ps:注意兩點1.構(gòu)造函數(shù)注入的值 奴璃;2.xml配置文件的對象的創(chuàng)建和注入旧找。
setxxx方法的注入方式 . . . .
- 詳細參考 :+ Spring 基于構(gòu)造函數(shù)的依賴注入