- Spring DI 教程
- Spring DI - 首頁
- Spring DI - 概述
- Spring DI - 環境搭建
- Spring DI - IOC 容器
- Spring 依賴注入
- Spring DI - 建立專案
- 基於建構函式的注入示例
- Spring DI - 基於建構函式的依賴注入
- Spring DI - 內部Bean建構函式注入
- Spring DI - 集合型別建構函式注入
- Spring DI - 集合引用建構函式注入
- Spring DI - Map型別建構函式注入
- Spring DI - Map引用建構函式注入
- 基於Setter方法的注入示例
- Spring DI - 基於Setter方法的依賴注入
- Spring DI - 內部Bean Setter注入
- Spring DI - 集合型別Setter注入
- Spring DI - 集合引用Setter注入
- Spring DI - Map型別Setter注入
- Spring DI - Map引用Setter注入
- 自動裝配示例
- Spring DI - 自動裝配
- Spring DI - 按名稱自動裝配
- Spring DI - 按型別自動裝配
- Spring DI - 建構函式自動裝配
- 工廠方法
- Spring DI - 靜態工廠方法
- Spring DI - 非靜態工廠方法
- Spring DI 有用資源
- Spring DI - 快速指南
- Spring DI - 有用資源
- Spring DI - 討論
Spring DI - 基於建構函式的依賴注入
基於建構函式的依賴注入是在容器呼叫類的建構函式,並傳入多個引數(每個引數代表對其他類的依賴)時實現的。
示例
以下示例顯示了一個只能透過建構函式注入進行依賴注入的類TextEditor。
讓我們更新在Spring DI - 建立專案章節中建立的專案。我們將新增以下檔案:
TextEditor.java - 一個包含SpellChecker作為依賴項的類。
SpellChecker.java - 一個依賴類。
MainApp.java - 執行和測試的主應用程式。
以下是TextEditor.java檔案的內容:
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
以下是另一個依賴類檔案SpellChecker.java的內容:
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
以下是MainApp.java檔案的內容。
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
以下是包含基於建構函式注入配置的配置檔案applicationcontext.xml:
<?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"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
輸出
建立原始檔和Bean配置檔案後,讓我們執行應用程式。如果應用程式一切正常,它將列印以下訊息:
Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling.
廣告