Spring入門學習筆記(1)
目錄
該篇隨筆,主要用於記錄Spring Framework 基礎知識。由於筆者是初學者,見識與能力有限,難免出現錯誤,如果發現錯誤,望不吝賜教。
Spring好處
以下列出了使用Spring Framework的一些巨大好處
-
Spring使開發人員能夠使用POJO開發企業級應用程式。僅使用POJO的好處是您不需要EJB容器產品(如應用程式伺服器),但您可以選擇僅使用強大的servlet容器(如Tomcat)或某些商業產品。
-
Spring採用模組化方式組織。即使包和類的數量很大,你也只需要擔心你需要的那些而忽略其餘的。
-
Spring並沒有重新發明輪子,而是真正利用了一些現有技術,如幾個ORM框架,日誌框架,JEE,Quartz和JDK計時器以及其他檢視技術。
-
測試用Spring編寫的應用程式很簡單,因為依賴於環境的程式碼被移動到這個框架中。此外,通過使用JavaBeanstyle POJO,使用依賴注入來注入測試資料變得更加容易。
-
Spring的Web框架是一個設計良好的Web MVC框架,它提供了一個很好的替代Web框架,如Struts或其他過度設計或不太流行的Web框架。
-
Spring提供了一個方便的API,用於將特定於技術的異常(例如,JDBC,Hibernate或JDO丟擲)轉換為一致的,未經檢查的異常。
-
輕量級IoC容器往往是輕量級的,尤其是與EJB容器相比時。這有利於在具有有限記憶體和CPU資源的計算機上開發和部署應用程式。
-
Spring提供了一致的事務管理介面,可以縮小到本地事務(例如,使用單個資料庫)並擴充套件到全域性事務(例如,使用JTA)。
依賴注入
- Inversion of Control
- 編寫java程式,儘可能獨立於其他java類,增加重用這些類的可能性
- 含義:A依賴於B類,意味著,B類將由IoC注入A類
面向面程式設計(AOP)
- 關鍵元件
- 跨領域問題:日誌記錄,宣告式事務,安全性,快取等
- AOP中,模組化單元是面
- AOP可幫助您將交叉問題與它們所影響的物件分離
- 允許定義方法攔截器和切入點,以便解耦。
Spring Framework
Core Container
-
Beans
- Core,提供了框架的基本部分,包括IOC/">IOC和依賴注入特徵
- Bean提供了BeanFactory,複雜的實現工廠模式
- Context由core和bean提供,它是訪問任何定義和配置的物件的媒介。ApplicationContext介面是上下文模組的焦點。
-
SpEL模組提供了一種強大的表示式語言,用於在執行時查詢和操作物件圖。
Data Access/Integration
- JDBC
- ORM 模組為流行的物件關係對映api提供整合層,包括JPA、JDO、Hibernate和iBatis
- OXM 模組提供了一個抽象層,支援JAXB、Castor、XMLBeans、JiBX和XStream的物件/XML對映實現。
- JMS 包含用於生成和消費訊息的特性。
- Transaction 模組為實現特殊介面的類和所有pojo支援程式設計和宣告式事務管理
Web
- Web Web模組提供了基本的面向Web的整合特性,例如多部分檔案上傳功能,以及使用servlet偵聽器和麵向Web的應用程式上下文初始化IoC容器。
- Web-MVC 模組包含Spring用於web應用程式的模型-檢視-控制器(MVC)實現。
- Web-Socket 模組在web應用程式中支援基於websocket的客戶機和伺服器之間的雙向通訊。
- Web-Portlet 模組提供了在portlet環境中使用的MVC實現,並反映了web servlet模組的功能。
Miscellaneous
- AOP模組提供了面向方面的程式設計實現,允許您將方法攔截器和切入點定義為實現應該分離的功能的乾淨解耦程式碼。
- Aspects模組提供了與AspectJ的整合,這又是一個強大而成熟的AOP框架。
- Instrumentation 模組提供了類插裝支援和類裝入器實現,用於某些應用伺服器。
- Messaging模組支援STOMP作為應用程式中使用的WebSocket子協議。它還支援一個註釋程式設計模型,用於路由和處理來自WebSocket客戶端的STOMP訊息。
- Test模組支援使用JUnit或TestNG框架測試Spring元件
編寫第一個程式
1.使用IDEA建立Spring專案
2.建立HelloWorld檔案
package top.ninwoo.learn; public class HelloWorld { private String message; public void getMessage() { System.out.println("Your message " + message); } public void setMessage(String message) { this.message = message; } }
3.建立Main函式
public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloworld"); obj.getMessage(); } }
使用ClassPathXmlApplicationContext讀取bean配置檔案
4.配置檔案
<?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.xsd"> <bean id="helloworld" class="top.ninwoo.learn.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>
property 傳入了HelloWorld的引數
IoC容器
- Spring Framework的核心
- 容器船艦物件,並連線彼此,並管理其生命週期
- DI來管理組成應用程式的元件
- 物件稱為Spring Beans
Spring IoC容器利用Java POJO類和配置元資料來生成完全配置和可執行的系統或應用程式,配置元資料可以由:
- XML
- Java註釋或Java程式碼表示
容器型別:
- Spring BeanFactory: 最簡單容器,目的向後相容與Spring整合的大量第三方框架
-
Spring ApplicationContext: 添加了更多企業特有的功能,比如能夠解析來自屬性檔案的文字訊息,
以及能夠向感興趣的事件偵聽器釋出應用程式事件。
ApplicationContext包含全部的BeanFactory,BeanFactory在小型化裝置上仍可以用。
Spring Bean
構成應用程式主幹並由Spring IoC容器管理的物件稱為bean.
Bean的定義:
- 如何建立Bean
- Bean的生命週期細節
- Bean的依賴關係
引數:
- class :必須,指定建立的Bean類
- name : 唯一指定Bean識別符號,XML中可以使用id/name來指定
- scope : 作用域
- construtor-arg : 用於注入依賴項
- properties : 用於注入依賴項
- autowiring mode : 用於注入依賴項
- lazy-initialization mode : 延遲初始化的bean告訴IoC容器在第一次請求時建立bean例項,而不是在啟動時建立
- initialization method : 在容器設定了bean之後所有必要屬性之後呼叫的回撥。它將在bean生命週期章節中討論
- destruction method : 當Bean容器被銷燬時使用的回撥。
Spring配置元資料
方法:
- XML
- 註解
- Java的配置
<?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"> <!-- A simple bean definition --> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with lazy init set on --> <bean id = "..." class = "..." lazy-init = "true"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with initialization method --> <bean id = "..." class = "..." init-method = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with destruction method --> <bean id = "..." class = "..." destroy-method = "..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
Spring - Bean Scopes
當定義一個
Spring Framework 支援以下5種作用域,如果使用的是web-aware Application只有三種可用。
- singleton : 將bean定義範圍限定為每個Spring IoC容器的單個例項(預設)
- prototype : 將bean定義範圍限定為具有任意數量的物件例項
- request : 將bean定義範圍限定為HTTP請求。僅在Web感知Spring ApplicationContext的上下文中有效
- session : 將bean定義範圍限定為HTTP會話。僅在Web感知Spring ApplicationContext的上下文中有效。
- global-session : 將bean定義範圍限定為全域性HTTP會話。僅在Web感知Spring ApplicationContext的上下文中有效。
singleton
只建立該Bean定義的物件的一個例項。
<!-- A bean definition with singleton scope --> <bean id = "..." class = "..." scope = "singleton"> <!-- collaborators and configuration for this bean go here --> </bean>
配置完成之後,如下的程式碼,有以下的效果。
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.setMessage("I'm object A"); objA.getMessage(); HelloWorld objB = (HelloWorld) context.getBean("helloWorld"); objB.getMessage();
該程式列印:
I'm object A I'm object A
這證明,實際只建立了一個bean物件,雖然呼叫了兩次getBean,但返回的都是同一個物件。
prototype
每次呼叫bean,都會建立一個新的方法。
將上述的bean設定為prototype,執行同樣的程式碼將會出現不同的效果。
該程式列印:
I'm object A null
Spring-Bean Life Cycle
主要指的是,當bean被例項化時,可能需要執行一些初始化以使其進入可用狀態。類似地,當不再需要bean並從容器中移除bean時,可能需要進行一些清理。
中間也存在一些活動,本章重點討論以下兩個宣告週期回撥方法。
- initmethod
- destroy-method
初始化回撥
org.springframework.beans.factory.InitializingBean已經為我們提供了開發介面。
void afterPropertiesSet() throws Exception;
這樣我們就可以通過實現上面的介面實現初始化工作
public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } }
另外,對於XML的配置元資料,可以通過init-method指定具有void無引數的方法
<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>
銷燬回撥
org.springframework.beans.factory.DisposableBean也已經提供好了介面
void destroy() throws Exception;
這樣,我們可以通過實現該介面實現銷燬的工作
public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work } }
注意:如果想要使該函式起作用,需要註冊registerShutdownHook()方法。
同樣,基於XML配置元資料,可以使用destroy-method指定具有void的無參方法
<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>
建議還是使用XML的方式,更加靈活。
預設的初始化和銷燬方法
如果很多bean都需要同名的初始化和銷燬方法,可以在
<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" default-init-method = "init" default-destroy-method = "destroy"> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean> </beans>