1. 程式人生 > >Spring入門學習筆記(1)

Spring入門學習筆記(1)

eth cast path jpa 組件 註解 lob 調用bean 應用

目錄

  • Spring好處
  • 依賴註入
  • 面向面編程(AOP)
  • Spring Framework
    • Core Container
    • Web
    • Miscellaneous
  • 編寫第一個程序
  • IoC容器
  • Spring Bean
    • Spring配置元數據
  • Spring - Bean Scopes
    • singleton
    • prototype
  • Spring-Bean Life Cycle
    • 初始化回調
    • 銷毀回調
    • 默認的初始化和銷毀方法

該篇隨筆,主要用於記錄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和依賴註入特征
    • 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的依賴關系

參數:

  1. class :必須,指定創建的Bean類
  2. name : 唯一指定Bean標識符,XML中可以使用id/name來指定
  3. scope : 作用域
  4. construtor-arg : 用於註入依賴項
  5. properties : 用於註入依賴項
  6. autowiring mode : 用於註入依賴項
  7. lazy-initialization mode : 延遲初始化的bean告訴IoC容器在第一次請求時創建bean實例,而不是在啟動時創建
  8. initialization method : 在容器設置了bean之後所有必要屬性之後調用的回調。它將在bean生命周期章節中討論
  9. 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>

Spring入門學習筆記(1)