第一章:Spring框架的介绍
1. Spring框架的概述
Spring是一个开放源代码的设计层面框架,它解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用。
Spring是于2003 年兴起的一个轻量级的Java开发框架,由Rod Johnson在其著作Expert One-On-One J2EE
Development and Design中阐述的部分理念和原型衍生而来。
它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。
Spring的核心是控制反转(IOC)和面向切面(AOP)。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
IOC:控制反转,将创建对象的过程交给spring进行管理
AOP:面向切面,在不修改源代码的情况之下进行代码功能的增强
2. Spring框架的优点
方便解耦,简化开发,Spring就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring管理,这也是IOC的作用。
AOP编程的支持,Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能。
声明式事务的支持,只需要通过配置就可以完成对事务的管理,而无需手动编程。
方便程序的测试,Spring对Junit4支持,可以通过注解方便的测试Spring程序。
方便集成各种优秀框架,Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts2、
Hibernate、MyBatis等)的直接支持。
降低JavaEE API的使用难度,Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail等),都提供了封装,使这些API应用难度大大降低。
第二章:创建Hello world
创建maven工程,导入坐标依赖
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
编写demo,编写具体的实现方法
package com.qcby.service; public class Demo { public void hello() { System.out.println("hello world"); } }
编写Spring核心的配置文件,在resources目录下创建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.xsd"> <!--IOC管理bean--> <!--id:类的唯一标识符 class:类的全路径名--> <bean id="demo" class="com.qcby.service.Demo" /> </beans>
编写测试方法。
package com.qcby.servic; import com.qcby.service.UserService; import com.qcby.service.UserServiceImpl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServiceTest { //传统写法 @Test public void run(){ Demo userService = new Demo(); userService.hello(); } //spring写法 @Test public void run1(){ //创建spring工厂,加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml"); //获取bean对象 Demo us = (Demo) ac.getBean("us"); //调用方法 us.hello(); } }