首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 系列(一):Spring 框架核心架構與 IoC、AOP 詳解

     編輯:Java 相關知識

Spring 框架概覽

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

七大模組架構

  • 核心容器:提供 BeanFactory,實現工廠模式與控制反轉(IoC),將配置與依賴從業務代碼中分離。
  • Spring 上下文:配置檔案提供 JNDI、EJB、郵件、國際化、驗證、調度等企業級服務。
  • Spring AOP:將面向切面編程整合進框架,支援宣告式事務管理,無需依賴 EJB。
  • Spring DAO:JDBC 抽象層提供有意義的異常層級,簡化錯誤處理與資源管理。
  • Spring ORM:整合 JDO、Hibernate、iBATIS SQL Maps,遵循統一事務與 DAO 異常體系。
  • Spring Web 模組:建立在應用上下文之上,支援 Struts 整合、多部分請求處理與參數綁定。
  • Spring MVC 框架:全功能 MVC 實現,高度可配置,支援 JSP、Velocity、Tiles、iText、POI 等視圖技術。

Spring 框架七大模組

核心概念:IoC 與 AOP

控制反轉(IoC)

基本思想:不在代碼中直接創建對象,而是在配置檔中描述創建方式與依賴關係,由容器負責實例化、裝配與生命週期管理。Spring 採用類型 2(Setter 注入)與類型 3(建構子注入)實現。

面向切面編程(AOP)

AOP 將橫切關注點(日誌、事務、安全)模組化為可重用的「切面」,以宣告方式應用於目標組件。業務類無需感知切面存在,實現鬆耦合。AOP 功能完全整合於 Spring 事務管理、日誌等上下文中。

IoC 容器深度解析

BeanFactory 與 XmlBeanFactory

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(郵件通知)。

Spring 配置實現鬆耦合整合

在 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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved