[原創]Spring教程01--Spring開始篇_Helloworld

weir發表於2018-01-20

開始之前

在寫這篇文章的時候;自己其實很猶豫;因為這個Spring的教程網上的教程也有很多。但是個人希望自己可以在底層儘量的詳細的總結一下;關於Spring的教程個人目標主要是底層的學習;可能這個是一個艱難的開始;期間可能有些錯誤,希望大家一同討論。

概敘

Spring的簡介:

Spring FrameWork目前已經發布Spring5.0了;Spring框架是一個全功能棧(full-stack)的應用程式框架。

Spring 的特點:

  • 輕量級:相較於EJB容器,Spring採用的IoC容器非常的輕量級,基礎版本的Spring框架大約只有2MB。Spring可以讓開發者們僅僅使用POJO(Plain Old Java Object,相對於EJB)就能夠開發出企業級的應用。這樣做的好處是,你不需要使用臃腫龐大的 EJB容器(應用伺服器),你只需要輕量的servlet容器(如Tomcat)。尤其在一些開發當中,很稀缺記憶體和CPU資源時,採用Spring比EJB無論是開發還是部署應用都更節約資源。
  • 控制反轉(IOC):Spring使用控制反轉技術實現了鬆耦合。依賴被注入到物件,而不是建立或尋找依賴物件。 面向切面程式設計(AOP): Spring支援面向切面程式設計,同時把應用的業務邏輯與系統的服務分離開來。
  • MVC框架:Spring MVC是一個非常好的MVC框架,可以替換其他web框架諸如Struts。 整合性:Spring非常容易和其他的流行框架一起整合開發,這些框架包括:ORM框架,logging框架,JEE, Quartz,以及Struts等表現層框架。
  • 事務管理:Spring強大的事務管理功能,能夠處理本地事務(一個資料庫)或是全域性事務(多個資料,採用JTA)。 模組分離:Spring框架是由模組構成的。雖然已經有太多的包和類了,但它們都按照模組分好類了,你只需要考慮你會用到的模組,而不用理其他的模組。
  • 異常處理:由於Java的JDBC,Hibernate等API中有很多方法丟擲的是checked exception,而很多開發者並不能很好的處理異常。Spring提供了統一的API將這些checked exception的異常轉換成Spring的unchecked exception。
  • 單元測試:Spring寫出來的程式碼非常容易做單元測試,可以採用依賴注射(Dependency Injection)將測試的資料注射到程式中。

Spring的歷史

直接文章釋出已經更新到SpringFramwork5.0;如果你想看其他版本的特性推薦《Spring歷史版本變遷和如今的生態帝國》參考博文

  • JDK更新
    Spring Framework 5.0 原來是計劃在 Java 9 之上發行的;現在,框架的最低要求是 Java 8。
  • 核心框架修正
    基於Java 8 所引入的新特性進行了修訂:
  • 基於 Java 8 的反射增強, Spring Framework 5.0 中的方法引數可以更加高效的進行訪問。
  • 核心的 Spring 介面現在提供基於Java 8 的預設方法構建的選擇性宣告。 用
  • @Nullable 和 @NotNull 註解來顯示錶明可為空的引數和以及返回值。這樣就夠在編譯的時候處理空值而不是在執行時丟擲 NullPointerExceptions

基於日誌記錄方面:

  • Spring Framework 5.0 帶來了 Commons Logging 橋接模組的封裝, 它被叫做 spring-jcl 而不是標準的 Commons Logging。當然,無需任何額外的橋接,新版本也會對 Log4j 2.x, SLF4J, JUL ( java.util.logging) 進行自動檢測。
  • 核心容器更新

Spring Framework 5.0 現在支援候選元件索引作為類路徑掃描的替代方案。該功能已經在類路徑掃描器中新增,以簡化新增候選元件標識的步驟。
可以在 Spring 的 Jira上瞭解更多關於元件索引的相關資訊

  • 含Kotlin在內的函數語言程式設計

引入了對 JetBrains Kotlin 語言的支援。Kotlin 是一種支援函數語言程式設計程式設計風格的面嚮物件語言。Kotlin 執行在 JVM 之上,但執行環境並不限於 JVM。

筆者對於Kotlin語言不是很熟悉;不做過多的評價。

  • 響應式程式設計模型

Spring 發行版本的一個激動人心的特性就是新的響應式堆疊 WEB 框架。這個堆疊完全的響應式且非阻塞,適合於事件迴圈風格的處理,可以進行少量執行緒的擴充套件。

後續針對這個做個專題的探討;Spring WebFlux

  • 測試改進

Spring Framework 5.0 完全支援 JUnit 5 Jupiter,所以可以使用 JUnit 5 來編寫測試以及擴充套件。此外還提供了一個程式設計以及擴充套件模型,Jupiter 子專案提供了一個測試引擎來在 Spring 上執行基於 Jupiter 的測試。 另外,Spring Framework 5 還提供了在 Spring TestContext Framework 中進行並行測試的擴充套件。
針對響應式程式設計模型, spring-test 現在還引入了支援 Spring WebFlux 的 WebTestClient 整合測試的支援,類似於 MockMvc,並不需要一個執行著的服務端。使用一個模擬的請求或者響應, WebTestClient 就可以直接繫結到 WebFlux 服務端設施

  • 庫支援

Spring Framework 5.0目前支援以下升級庫的版本 :

  • Spring Framework 5.0目前支援以下升級庫的版本 :
  • Jackson 2.6+
  • EhCache 2.10+ / 3.0 GA
  • Hibernate 5.0+
  • JDBC 4.0+
  • XmlUnit 2.x+
  • OkHttp 3.x+
  • Netty 4.1+
  • 中止支援

在 API 層面,Spring Framework 5.0 不再支援以下包:

  • beans.factory.access
  • jdbc.support.nativejdbc
  • spring-aspects 模組的 mock.staticmock
  • web.view.tiles2M.(最低要求 Tiles 3)
  • orm.hibernate3 和 orm.hibernate4.

目前 Hibernate 5 是支援的框架。

  • Portlet.
  • Velocity.
  • JasperReports.
  • XMLBeans.
  • JDO.
  • Guava.
    如果你正在使用任何上面的包,建議你將 Spring Framework 版本維持在 4.3.x。

快速開始

Spring官方其實推薦使用SpringBoot構建Spring框架程式,但是這裡重點關注Spring的框架的內容;所以這裡使用Spring框架搭建;後期有機會搭建SpringBoot的教程和資料。

開發環境

  • eclipse或者IDEA
  • JDK8(推薦)/7
  • Spring Framwork5

開始

  1. 構建Maven的工程;工程目錄如下:

  2. 使用註解方式的Helloworld:

pom.xml檔案:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
</dependencies>
複製程式碼

hello/MessageService.java

package hello.annotation;

public interface MessageService {
    String getMessage();
}
複製程式碼

hello/MessagePrinter.java

package hello.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessagePrinter {

    final private MessageService service;

    @Autowired
    public MessagePrinter(MessageService service) {
        this.service = service;
    }

    public void printMessage() {
        System.out.println(this.service.getMessage());
    }
}
複製程式碼

hello/Application.java

package hello.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan
public class Application {

    @Bean
    MessageService mockMessageService() {
        return new MessageService() {
            public String getMessage() {
              return "Hello World!";
            }
        };
    }

  public static void main(String[] args) {
      ApplicationContext context = 
          new AnnotationConfigApplicationContext(Application.class);
      MessagePrinter printer = context.getBean(MessagePrinter.class);
      printer.printMessage();
  }
}
複製程式碼
  1. 使用xml檔案配置: applicationContext.xml
<?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">

   <bean id="MessageService" class="hello.xml.MessageService">
       <property name="message" value="Hello World!"/>
   </bean>
</beans>
複製程式碼

MessageService.java

package hello.xml;

public class MessageService {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}
複製程式碼

Application.java

package hello.xml;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
	public static void main(String[] args) {
		ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
		MessageService messageService = application.getBean(MessageService.class);
		System.out.println(messageService.getMessage());
	}
}

複製程式碼

4.執行結果:

執行結果

簡要講解:

  1. 根據配置檔案獲知配置類初始化ApplicationContet容器
  2. 根據配置注入Bean物件(MessageService)
  3. 容器例項化動態建立Bean物件 其實上述的;底層使用工廠的建立模式;Spring容器統一建立管理Java的Bean物件;關於這個具體的分析後續具體講解。

參考資料:


相關文章