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的接口或者类。