1 Spring介绍
1.1 Spring概述
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益
简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
1.2 Spring好处
方便解耦,简化开发:
Spring就是一个大工厂,专门负责生成Bean,可以将所有对象创建和依赖关系维护由Spring管理
AOP编程的支持:
Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
声明式事务的支持:
只需要通过配置就可以完成对事务的管理,而无需手动编程
方便程序的测试:
Spring对Junit4支持,可以通过注解方便的测试Spring程序
方便集成各种优秀框架:
Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的支持
降低JavaEE API的使用难度 Spring:
对JavaEE开发中一些难用的API(JDBC、JavaMail、远程调webservice用等),都提供了封装,使这些API应用难度大大降低
1.3 Spring体系结构
Spring 框架是一个分层架构,它包含一系列的功能要素并被分为大约20个模块。这些模块分为Core Container、Data Access/Integration、Web、AOP(Aspect Oriented Programming)、Instrumentation和测试部分,如下图所示:
1.4 在项目中的架构
web层:Struts,SpringMVC
dao层:Hibernate,mybatis
2.Spring的入门案例
第一步:
创建一个Meaven项目
第二步:
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
第三步:
编写配置文件
<?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">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
第四步:
将对象加入容器
<bean id="serviceImpl" class="com.xzh.service.impl.ServiceImpl"></bean>
<bean id="log" class="com.xzh.log.Log"></bean>
<bean id="afterLog" class="com.xzh.log.AfterLog"></bean>
<bean id="diy" class="com.xzh.diy.Diy"></bean>
<bean id="annotation" class="com.xzh.annotation.Annotation"></bean>
第五步:
从beans.xml获取bean
package test;
import com.xzh.service.Service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Tesr {
public static void main(String[] args) {
ApplicationContext ioc = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Service impl = ioc.getBean("serviceImpl", Service.class);
}
}
总结:【IoC】
1) IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架
2.5 DI解释
Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。
例子:
在UserService中提供一个get/set的name方法,在beans.xml中通过property去注入