Spring 是為了解決企業級應用開發複雜性而誕生的開源框架。其核心優勢在於分層架構:七大模組建立在核心容器之上,開發者可按需選擇組件,同時享有整合框架的便利。

基本思想:不在代碼中直接創建對象,而是在配置檔中描述創建方式與依賴關係,由容器負責實例化、裝配與生命週期管理。Spring 採用類型 2(Setter 注入)與類型 3(建構子注入)實現。
AOP 將橫切關注點(日誌、事務、安全)模組化為可重用的「切面」,以宣告方式應用於目標組件。業務類無需感知切面存在,實現鬆耦合。AOP 功能完全整合於 Spring 事務管理、日誌等上下文中。
org.springframework.beans.factory.BeanFactory 是工廠模式實現,允許按名稱檢索對象並管理對象關係。最常用實現 XmlBeanFactory 根據 XML 定義載入 Bean:
BeanFactory factory = new XmlBeanFactory(new FileInputStream("mybean.xml"));
MyBean mybean = (MyBean) factory.getBean("mybean");
Bean 定義可為 POJO 或 FactoryBean,支援單例與原型兩種模型。
三個獨立服務介面:CreditRatingInterface(信用評級)、CreditLinkingInterface(遠程資訊鏈接)、EmailInterface(郵件通知)。
在 CreateCreditCardAccount 類中,透過 Setter 方法注入三個服務介面,業務邏輯僅調用介面方法。Spring 配置檔(springexample-creditaccount.xml)定義 Bean 與依賴關係:
<bean id="creditRating" class="springexample.creditaccount.CreditRating"/>
<bean id="creditLinking" class="springexample.creditaccount.CreditLinking">
<property name="url" value="https://remotehost:8080/creditlinking"/>
</bean>
<bean id="email" class="springexample.creditaccount.Email">
<property name="smtpHost" value="mail.example.com"/>
<property name="userId" value="admin"/>
<property name="password" value="secret"/>
</bean>
<bean id="createCreditCard" class="springexample.creditaccount.CreateCreditCardAccount">
<property name="creditRating" ref="creditRating"/>
<property name="creditLinking" ref="creditLinking"/>
<property name="email" ref="email"/>
</bean>
使用 ClassPathXmlApplicationContext 載入配置,獲取 Bean 執行業務流程:
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[]{"springexample-creditaccount.xml"});
CreateCreditCardAccountInterface creditCardAccount =
(CreateCreditCardAccountInterface) appContext.getBean("createCreditCard");
本文介紹了 Spring 分層架構、IoC 容器與 AOP 核心機制,並透過信用卡開戶案例展示了依賴注入如何以鬆耦合方式整合分散系統。下一篇將深入 Spring AOP 與持久化支援,並引入 Spring MVC。