Spring框架是以簡化J2EE應用程序開發爲特定目標而建立的,是當前最流行的Java開發框架。java
本書從介紹Spring框架入手,針對Spring4.3和Java8介紹bean的配置、依賴注入、定義bean、基於Java的容器、AOP、Spring Data、Spring MVC等知識,旨在幫助讀者更輕鬆的學習Spring框架的方法。web
簡介spring
一、建立結構良好、易於維護和易於測試的應用程序是開發者的職責shell
二、Spring框架是SpringSource出品的一個用於簡化Java企業級應用開發的開源應用程序框。他提供了開發一個結構良好的,可維護和易於測試的應用所需的基礎設施數據庫
三、Spring框架的核心是提供了依賴注入(Dependency Injection,DI)機制的控制反轉(Inversion of Control,IoC)容器。express
注意:在本書中,咱們將以一個名爲MyBank的網上銀行應用爲例,介紹Spring框架的功能
Spring框架有多個模塊組成,他們提供應用開發功能進行分組,下面描述Spring框架中各個模塊組編程
模塊組 | 描述 |
---|---|
Core container | 包含構成Spring框架基礎的模塊,該組中的spring-core和spring-beans模塊提供了Spring的DI功能和IoC容器實現。spring-expressions模塊爲在Spring應用中經過Spring表達式語言配置應用程序對象提供了支持 |
AOP and instrumentation | 包含支持AOP(面向切面編程)和類工具模塊,The spring-aop模塊提供了Spring的AOP功能spring-instrument提供了對類工具的支持 |
Messaging | 包含簡化開發基於消息的應用的spring-messaging模塊 |
Data Access/Integration | 包含簡化與數據庫和消息提供者交互的模塊。spirng-jdbc模塊簡化了用JDBC於數據庫交互,spring-orm模塊提供了與ORM(對象映射關係)框架的集成,如JPA何Hibernate。spring-jms模塊簡化了與JMS提供者的交互。此模塊組還包含了spring-tx模塊,該模塊提供了編程式與聲明式事務管理 |
Web | 包含簡化開發web和portlet應用的模塊。spirng-web和spirng-webmvc模塊都是用於開發web應用和RESTful的web服務的。spring-websocket模塊支持使用WebSocket開發Web應用 |
Test | 包含spirng-test模塊,該模塊簡化了建立單元和集成測試 |
//讀者注:spring websocket用於實現先後端通訊
==總結==後端
如圖所示,Spring涵蓋了企業應用程序開發的各個方面,可使用Spring開發Web應用程序、訪問數據庫、管理事務、建立單元測試和集成測試等。在設計Spring框架模塊時,你只須要引入應用程序所須要的模塊。例如,在應用程序中使用Spring的DI功能,只須要引入Core container組中的模塊設計模式
一個Java應用程序,由互相調用以提供應用程序行爲的一組對象組成。某個對象調用其餘對象稱爲它的依賴項,例如,若是對象X調用了對象Y和Z,那麼Y和Z就是對象X的依賴項。DI是一種設計模式,其中對象的依賴項一般被指定爲其構造函數和setter方法的參數。而且,這些依賴項將在這些對象建立時注入到該對象中。websocket
在Spring應用程序中,Spring IoC容器負責建立應用程序對象並注入他們的依賴項。Spring容器建立和管理的應用對象稱爲Bean。因爲Spring容器負責將應用程序對象組合在一塊兒,所以不須要實現諸如工廠或者服務定位器等設計模式來構成應用。由於建立和注入依賴項的不是應用程序的對象,而是Spring容器。因此DI也稱爲控制反轉(IoC)。
假設MyBank應用程序包含FixedDepositController和FixedDepositService兩個對象。FixedDepositController依賴於FixedDepositService。
package sample.spring.chapter01.bankapp; //由於FixedDepositController調用了FixedDepositService,因此FixedDepositService就是FixedDepositController的依賴項 public class FixedDepositController { private FixedDepositService fixedDepositService; //建立FixedDepositController的構造函數 //用於調用FixedDepositService的save方法 public FixedDepositController(){ fixedDepositService = new FixedDepositService(); } // public boolean submit(){ //保存按期存款明細 fixedDepositService.save(); return true; } }
若是將FixedDepositController配置爲一個Spring Bean,首先要修改程序實例中的FixedDepositController類,讓他接收FixedDepositService依賴做爲構造函數或者setter方法的參數,修改後的FixedDepositController類。
package sample.spring.chapter01.bankapp; public class FixedDepositController { private FixedDepositService fixedDepositService; public FixedDepositController(FixedDepositService fixedDepositService){ this.fixedDepositService = fixedDepositService; } public boolean submit(){ fixedDepositService.save(); return true; } }
FixedDepositService示例如今已經做爲構造函數參數傳遞到FixedDepositController實例中,如今的FixedDepositService類能夠配置一個Spring bean。注意,FixedDepositController類並無實現或者繼承任何spring的接口或者類。