IOC(控制反轉)聽起來抽象,但用最少的程式碼就能把核心機制寫出來。本文動手實作一個支援註解驅動注入的簡易容器,只需要五個部分。
需要被容器管理的類別全部繼承這個基類。
package com.metarnet.extend;
import java.lang.reflect.Field;
import com.metarnet.Injects.Inject;
/** 容器 */
public class IOC {
/**
* 初始化:掃描自身宣告的欄位,對帶有 @Inject 的欄位執行注入
*/
public void Init() throws Exception {
Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
field.setAccessible(true);
field.set(this, Class.forName(inject.ClassName().trim()).newInstance());
}
}
}
}
這段程式碼是整個容器的全部智慧所在,拆解成三步:
1. getClass().getDeclaredFields() 取得執行期物件的型別,列出它自己宣告的所有欄位。注意這裡用的是子類別傳進來的 getClass(),所以掃描的是繼承 IOC 的那個類別。
2. field.getAnnotation(Inject.class) 判斷該欄位有沒有標註解。
3. 有的話,用 Class.forName(...).newInstance() 依註解裡指定的全限定類名動態建立物件,再透過反射塞進欄位。
setAccessible(true) 這行不能省——因為被注入的欄位通常是 private,預設情況下反射無法寫入。
package com.metarnet.Injects;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** 類的依賴注入 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
public String ClassName();
}
兩個 meta-annotation 都是必要的:@Target(ElementType.FIELD) 限定這個註解只能標在欄位上;@Retention(RetentionPolicy.RUNTIME) 則要求註解資訊保留到執行期,少了這一行,反射讀不到註解,容器會靜默地什麼都不做——這是自行實作註解時最常見的失誤。
package com.metarnet.Main;
import com.metarnet.Injects.Inject;
import com.metarnet.Interfaces.Interface1;
import com.metarnet.extend.IOC;
public class TestIOC extends IOC {
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl")
private Interface1 interface1;
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl2")
private Interface1 interface2;
public Interface1 getInterface1() {
return interface1;
}
public void setInterface1(Interface1 interface1) {
this.interface1 = interface1;
}
public static void main(String[] args) {
TestIOC ioc = new TestIOC();
try {
ioc.Init();
} catch (Exception e) {
e.printStackTrace();
}
ioc.interface1.SayHello();
ioc.interface2.SayHello();
}
}
值得留意的是這裡的設計意圖:interface1 與 interface2 宣告的型別完全相同(都是 Interface1),但注入的實作類別不同。呼叫端只認得介面,換實作只需改註解字串,一行程式邏輯都不用動——這就是依賴注入的價值所在。
package com.metarnet.Interfaces;
public interface Interface1 {
public void SayHello();
}
// 實作一
package com.metarnet.Interfaces.imps;
import com.metarnet.Interfaces.Interface1;
public class Interface1Impl implements Interface1 {
@Override
public void SayHello() {
System.out.println("Hello World, My Name Is Interface1Impl");
}
}
// 實作二
package com.metarnet.Interfaces.imps;
import com.metarnet.Interfaces.Interface1;
public class Interface1Impl2 implements Interface1 {
@Override
public void SayHello() {
System.out.println("Hello World, My Name Is Interface1Impl2");
}
}
動手做一遍之後,也該清楚它與正式框架的距離:
每次都是 new。容器每次都建立新物件,沒有任何生命週期管理,也不支援 singleton 或 prototype 的作用域概念。真實場景中,注入进来的物件往往是共用實例。
只支援建構後的欄位注入。沒有 setter 注入、沒有建構子注入,因此無法表達「這個依賴是必填的」這類約束——如果 Class.forName 失敗,只會得到一個 null 欄位,直到第一次使用才爆 NullPointerException。
類名字寫死在註解裡。字串形式的類名失去編譯期檢查,重構時 IDE 也不會幫你改。實務上通常改成讀取外部設定檔(XML、properties 或 YAML),讓組態與程式碼分離。
錯誤處理過於寬鬆。目前 Init() 直接拋出 Exception 給呼叫端,較好的做法是在容器層彙整成專屬的例外型別,並在訊息中帶上是哪個欄位、哪個類名注入失敗。
儘管如此,這不到三十行的容器已經完整呈現了 IOC 的三個要素:反射取得型別、註解宣告意圖、動態建立並注入。理解這三點之後,再去看 Spring 的 BeanFactory 與 BeanDefinition,會發現架構複雜度增加的部分都在處理邊界條件(生命週期、作用域、循環依賴、AOP 整合),核心機制其實與此同源。