Spirng学习指南-第一天,
Spirng学习指南-第一天,
Spring学习指南
内容提要
Spring框架是以简化J2EE应用程序开发为特定目标而创建的,是当前最流行的Java开发框架。
本书从介绍Spring框架入手,针对Spring4.3和Java8介绍bean的配置、依赖注入、定义bean、基于Java的容器、AOP、Spring Data、Spring MVC等知识,旨在帮助读者更轻松的学习Spring框架的方法。
第一章 Spring框架简介
简介
1、创建结构良好、易于维护和易于测试的应用程序是开发者的职责
2、Spring框架是SpringSource出品的一个用于简化Java企业级应用开发的开源应用程序框。他提供了开发一个结构良好的,可维护和易于测试的应用所需的基础设施
3、Spring框架的核心是提供了依赖注入(Dependency Injection,DI)机制的控制反转(Inversion of Control,IoC)容器。
注意:在本书中,我们将以一个名为MyBank的网上银行应用为例,介绍Spring框架的功能
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组中的模块
Spring IoC容器
一个Java应用程序,由互相调用以提供应用程序行为的一组对象组成。某个对象调用其他对象称为它的依赖项,例如,如果对象X调用了对象Y和Z,那么Y和Z就是对象X的依赖项。DI是一种设计模式,其中对象的依赖项通常被指定为其构造函数和setter方法的参数。并且,这些依赖项将在这些对象创建时注入到该对象中。
在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的接口或者类。
相关文章
- 暂无相关文章
用户点评