SSM框架复习2
Spring
理念:使现有的技术更加容易使用,整合了现有的框架
核心:IoC Container, Events, Resources, i18n, Validation, Data Binding, Type Conversion, SpEL, AOP
官网:https://spring.io/
下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
github地址:https://github.com/spring-projects/spring-framework
优点
- spring是一个开源免费的框架、容器
- spring是一个轻量级的框架,非侵入式的
- 控制反转IOC,面向切面AOP
- 对事务支持,对框架支持
Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器(框架)
组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:
核心容器: 核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
Spring 上下文: Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
Spring AOP: 通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
Spring DAO: JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
Spring ORM: Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
Spring Web 模块: Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
Spring MVC 框架: MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。
IOC
IOC本质
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IoC的另一种说法。没有IOC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方;获得依赖对象的方式反转了。
IoC是Spring框架的核心内容, 使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。
spring ioc容器的设置
核心接口: beanFactory ApplicationContext
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
总的来说:控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
代码实现:
导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
2、编写代码
Student类
public class Student {
private int studentNo;
private String studentName;
private String sex;
public int getStudentNo() {
return studentNo;
}
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
编写spring文件,(基于XML的配置元数据)这里我们命名为beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用spring创建一个对象-->
<bean id="student" class="com.flyfly.sp.pojo.Student">
<property name="studentName" value="flyfly" />
</bean>
</beans>
测试
public class Spring01Test {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
Student student= (Student) context.getBean("student");
System.out.println(student.toString());
}
}
注:这里可能会扫描不到beans.xml文件,会报错无法找到[beans.xml]resource;解决:在pom.xml文件中配置
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- Student对象是谁创建的 ? 【Student】对象是由Spring创建的
- Student对象的属性是怎么设置的 ? Student对象的属性是由Spring容器设置的 这个过程就叫控制反转 :
控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
反转 : 程序本身不创建对象 , 而变成被动的接收对象 .
依赖注入 : 就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的编程变成被动的接收
Spring配置
<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>
<!--bean就是java对象,由Spring创建和管理-->
<!--
id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
如果配置id,又配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
class是bean的全限定名=包名+类名
-->
<bean id="student" name="s1,s2,s3" class="com.flyfly.sp.pojo.Student">
<property name="name" value="Spring"/>
</bean>
<!--团队的合作通过import来实现 .-->
<import resource="{path}/beans.xml"/>
spring bean的生命周期
1>初始化类
2>依赖注入
3>BeanName :获得类的名字
4>BeanFactory:通过名字获得对象
5>获得applicationContext容器
6>开始实例化
7>加载配置文件
8>自定义初始化的方法
9>实例化完成
10>调用方法方法
11>调用销毁的方法
12>调用自定义销毁的方法
DI(Dependency Injection)—set/cp
- 依赖注入(Dependency Injection,DI)。
- 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
- 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .
注入方式:构造注入、setter注入
Spring的两种依赖注入方式:setter注入与构造方法注入,这两种方法的不同主要就是在xml文件下对应使用property和constructor-arg属性
property属性:<property name="id" value="123"></property>(其中name的值为原类中的属性名)
constructor-arg属性:<constructor-arg index="0" value="456"></constructor-arg>(其中index的值为0~n-1,n代表构造函数中的输入参数的数量)
1.构造方法注入
容器调用带有一组参数的类构造方法完成依赖注入,使用的是〈bean〉标签中的〈constructor-arg〉元素
在xml中添加bean,使用构造器注入属性值,使用value属性进行参数值的注入
<?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="student" class="com.flyfly.sp.pojo.Student">
<constructor-arg value="张三"/>
<constructor-arg value="18"/>
</bean>
</beans>
1)多个参数时,把参数传递给构造函数可能会存在歧义
可以使用 index 属性来显式的指定构造函数参数的索引,索引从0开始
修改< bean >定义如下:
<bean id="student" class="com.flyfly.sp.pojo.Student">
<constructor-arg index="0" value="张三"/>
<constructor-arg index="1" value="18"/>
</bean>
2)使用type属性指定参数的类型
注意:基本类型有包装类型需要进行区分
修改< bean >定义如下:
<bean id="student" class="com.flyfly.sp.pojo.Student">
<constructor-arg index="0" type="java.lang.String" value="张三"/>
<constructor-arg index="1" type="java.lang.Integer" value="18"/>
</bean>
3)需要给参数指定一个引用(指向其他bean),使用ref属性
修改xml。添加一个bean定义
<bean id="student" class="com.flyfly.sp.pojo.Student">
<constructor-arg ref="teacher"/>
</bean>
2.setter方法注入
setter方法注入即是创建一个普通的JavaBean类,要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .
<!--1、常量注入-->
<bean id="student" class="com.flyfly.pojo.Student">
<property name="studentName" value="flyfly" />
</bean>
<!--2、Bean注入-->
<bean id="addr" class="com.flyfly.pojo.Address">
<property name="address" value="北京"/>
</bean>
<bean id="student" class="com.flyfly.pojo.Student">
<property name="name" value="flyfly"/>
<property name="address" ref="addr"/>
</bean>
<!--3、数组注入-->
<bean id="student" class="com.flyfly.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
<!--4、List注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>爬山</value>
</list>
</property>
<!--5、Map注入-->
<property name="card">
<map>
<entry key="中国邮政" value="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>
<!--6、set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!--6、Null注入-->
<property name="son"><null/></property>
<!--6、Properties注入-->
<property name="info">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>
</bean>
p命名和c命名注入
1、P命名空间注入 : 需要在头文件中加入约束文件
<!--导入约束 : xmlns:p="http://www.springframework.org/schema/p"-->
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.flyfyl.pojo.User" p:name="fltyfly" p:age="18"/>
2、c 命名空间注入 : 需要在头文件中加入约束文件
<!--导入约束 : xmlns:c="http://www.springframework.org/schema/c"-->
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.flyfly.pojo.User" c:name="flyfly" c:age="18"/>
注:c命名空间注入需要把有参构造器加上
Bean的作用域
其中 request、session作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。
Singleton
当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:
<bean id="ServiceImpl" class="cn.fly.service.ServiceImpl" scope="singleton">
Prototype
当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:
<bean id="account" class="com.fly.DefaultAccount" scope="prototype"/>
或者
<bean id="account" class="com.fly.DefaultAccount" singleton="false"/>
Request
当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:
<bean id="loginAction" class="com.fly.LoginAction" scope="request"/>
针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。
Session
当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:
<bean id="userPreferences" class="com.fly.UserPreferences" scope="session"/>
针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。
使用注解
1、在spring配置文件中引入context文件头;2、开启属性注解支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/beans/spring-aop.xsd"
>
<!--指定注解扫描包-->
<context:component-scan base-package="com.flyfly.pojo"/>
<!--开启注解支持-->
<context:annotation-config/>
</beans>
@Autowired
- @Autowired是按照类型自动转配的,不支持id匹配
- 需要导入spring-aop的包
<!--如果一个类声明了多个构造函数,但都没有用注释@Autowired,
则将使用主/默认构造函数(如果存在)。如果一个类只声明一个单一的构造函数开始,
即使没有注释,也将始终使用它。请注意,带注释的构造函数不必是公共的。
@Autowired(required=false)说明:false,对象可以为null;true,对象必须存在对象
@Qualifier(value="student1")说明:当同一个类有多个bean时,可以加上注解 @Qualifier(value="id名")
-->
@Autowired(required=false)
@Qualifier(value="student1")
private Teacher teacher;
@Resource
- @Resource如果有指定的name属性,先按该属性进行byName方式查找装配
- 其次再进行默认的byName方式进行装配
- 如果以上都不成功,则按照byType的方式自动装配
@Resource
private Teacher teacher;
@Component
作用域 @scope
singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Component("user")
@Scope("prototype")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
@Value("flyfly")
// 相当于配置文件中 <property name="name" value="flyfly"/>
public String name;
//如果提供了set方法,在set方法上添加@value("值");
@Value("flyfly")
public void setName(String name) {
this.name = name;
}
}
衍生注解
@Component三个衍生注解
- @Controller:web层
- @Service:service层
- @Repository:dao层
XML与注解比较
- XML可以适用任何场景 ,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便
xml与注解整合开发 :推荐最佳实践
- xml管理Bean
- 注解完成属性注入
- 使用过程中, 可以不用扫描,扫描是为了类上的注解
<context:annotation-config/>
作用:
- 进行注解驱动注册,从而使注解生效
- 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
- 如果不扫描包,就需要手动配置bean
- 如果不加注解驱动,则注入的值为null
代理模式(静态、动态)
静态代理
静态代理角色分析
- 抽象角色 : 一般使用接口或者抽象类来实现
- 真实角色 : 被代理的角色
- 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .
- 客户 : 使用代理角色来进行一些操作 .
代码实现
SellCar. java 即抽象角色
//抽象角色:卖车
public interface SellCar{
public void sellCar();
}
CarOwner . java 即真实角色
//真实角色: 车主,车主要卖车
public class CarOwner implements SellCar{
public void SellCar() {
System.out.println("车要卖出");
}
}
Proxy . java 即代理角色
//代理角色:中介
public class Proxy implements SellCar {
private CarOwner carOwner ;
public Proxy() { }
public Proxy(CarOwner carOwner ) {
this.carOwner = carOwner ;
}
//卖车
public void sellCar(){
seeCar();
carOwner.SellCar();
fare();
}
//看车
public void seeHCar(){
System.out.println("带客看车");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
}
Client . java 即客户
//客户类,一般客户都会去找代理!
public class Client {
public static void main(String[] args) {
//车主要卖车
CarOwner carOwner = new CarOwner();
//中介帮助车主
Proxy proxy = new Proxy(carOwner);
//你去找中介!
proxy.sellCar();
}
}
分析:在这个过程中,你直接接触的就是中介,就如同现实生活中的样子,你看不到二手车车主,但是你依旧买到了车主的车通过代理,这就是所谓的代理模式,程序源自于生活,所以学编程的人,一般能够更加抽象的看待生活中发生的事情。
静态代理的好处:
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 。
- 公共的业务由代理来完成 . 实现了业务的分工 ,
- 公共业务发生扩展时变得更加集中和方便 .
缺点 :
- 类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .
我们想要静态代理的好处,又不想要静态代理的缺点,所以 , 就有了动态代理 !
动态代理
- 动态代理的角色和静态代理的一样 .
- 动态代理的代理类是动态生成的 . 静态代理的代理类是我们提前写好的
- 动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理
- 基于接口的动态代理----JDK动态代理
- 基于类的动态代理–cglib
- 现在用的比较多的是 javasist 来生成动态代理 . 百度一下javasist
- 我们这里使用JDK的原生代码来实现,其余的道理都是一样的!
JDK的动态代理需要了解两个类
核心 : InvocationHandler 和 Proxy , 打开JDK帮助文档看看
【InvocationHandler:调用处理程序】
Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
【Proxy : 代理】
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),this);
}
代码实现
抽象角色和真实角色和之前的一样!
SellCar. java 即抽象角色
//抽象角色:卖车
public interface SellCar{
public void sellCar();
}
CarOwner . java 即真实角色
//真实角色: 车主,车主要卖车
public class CarOwner implements SellCar{
public void SellCar() {
System.out.println("车要卖出");
}
}
ProxyInvocationHandler. java 即代理角色
public class ProxyInvocationHandler implements InvocationHandler {
private SellCar sellCar;
public void setSellCar(SellCar sellCar) {
this.sellCar= sellCar;
}
//生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
sellCar.getClass().getInterfaces(),this);
}
// proxy : 代理类 method : 代理类的调用处理程序的方法对象.
// 处理代理实例上的方法调用并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeCar();
//核心:本质利用反射实现!
Object result = method.invoke(sellCar, args);
fare();
return result;
}
//看车
public void seeCar(){
System.out.println("带客户看车");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
}
Client . java
//买客
public class Client {
public static void main(String[] args) {
//真实角色
CarOwner carOwner = new CarOwner ();
//代理实例的调用处理程序
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setSellCar(carOwner ); //将真实角色放置进去!
SellCar proxy = (SellCar)pih.getProxy(); //动态生成对应的代理类!
proxy.sellCar();
}
}
核心:一个动态代理 , 一般代理某一类业务 , 一个动态代理可以代理多个类,代理的是接口!
深入
我们使用动态代理实现代理我们后面写的UserService!
我们也可以编写一个通用的动态代理实现的类!所有的代理对象设置为Object即可!
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
// proxy : 代理类
// method : 代理类的调用处理程序的方法对象.
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String methodName){
System.out.println("执行了"+methodName+"方法");
}
}
public class Test {
public static void main(String[] args) {
//真实对象
UserService userService = new UserServiceImpl();
//如果需要改变调用的实现类,只需要,修改new UserServiceImpl()
//代理对象的调用处理程序
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService); //设置要代理的对象
UserService proxy = (UserService)pih.getProxy(); //动态生成代理类!
proxy.delete();
}
}
动态代理的好处
静态代理有的它都有,静态代理没有的,它也有!
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情
- 公共的业务由代理来完成 . 实现了业务的分工
- 公共业务发生扩展时变得更加集中和方便 .
- 一个动态代理 , 一般代理某一类业务
- 一个动态代理可以代理多个类,代理的是接口!
AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
Aop在Spring中的作用**
提供声明式事务;允许用户自定义切面
以下名词需要了解下:
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 ,
缓存 , 事务等等 … - 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
- 前置通知:方法执行前:org.springframework.aop.MethodBeforeAdvice;
- 后置通知:方法执行后:org.springframework.aop.AfterReturningAdvice;
- 环绕通知:方法执行前后:import org.aopalliance.intercept.MethodInterceptor;
- 异常抛出通知:方法抛出异常:org.springframework.aop.ThrowsAdvice;
- 引介通知:类中增加新的方法属性:org.springframework.aop.IntroductionInterceptor;
即 Aop 在 不改变原有代码的情况下 , 去增加新的功能 .
使用Spring实现Aop
第一种方式:通过 Spring API 实现
1、首先编写我们的业务接口和实现类
public interface StudentService {
void add();
void update();
void delete();
void select();
}
public class StudentServiceImpl implements StudentService {
@Override
public void add() {
System.out.println("增加学生信息");
}
@Override
public void update() {
System.out.println("修改学生信息");
}
@Override
public void delete() {
System.out.println("删除学生信息");
}
@Override
public void select() {
System.out.println("查询学生信息");
}
}
2、写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强
public class Log implements MethodBeforeAdvice {
/**
* @param method 要执行目标对象的方法
* @param args 参数
* @param target 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
/**
* @param returnValue 结果返回值
* @param method
* @param args
* @param target
* @throws Throwable
*/
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回了"+returnValue);
}
}
3、spring的文件中注册 , 并实现aop切入实现 , 注意导入约束 .
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<bean id="studentService" class="com.flyfly.sp.service.impl.StudentServiceImpl"/>
<bean id="log" class="com.flyfly.sp.log.Log"/>
<bean id="afterLog" class="com.flyfly.sp.log.AfterLog"/>
<!--方式一:aop的配置-->
<aop:config>
<!--切入点 expression:表达式匹配要执行的方法-->
<aop:pointcut id="pointcut" expression="execution(* com.flyfly.sp.service.impl.StudentServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试
public class SpringTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//动态代理一个接口
StudentService studentService =(StudentService) context.getBean("studentService");
studentService.select();
}
}
Aop的重要性 : 很重要 .
一定要理解其中的思路 , 主要是思想的理解这一块 .
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .
方式二:使用AOP的标签实现:只需要改beans.xml
1、编写自己的切入类
public class customLog {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
修改beans.xml
<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="customLog" class="com.flyfly.sp.log.customLog"/>
<!--aop的配置-->
<aop:config>
<!--第二种方式:使用AOP的标签实现-->
<aop:aspect ref="customLog">
<aop:pointcut id="customPonitcut" expression="execution(* com.flyfly.sp.service.impl.StudentServiceImpl.*(..))"/>
<aop:before pointcut-ref="customPonitcut" method="before"/>
<aop:after pointcut-ref="customPonitcut" method="after"/>
</aop:aspect>
</aop:config>
第三种方式:使用注解实现
1、编写注解增强类
@Aspect
public class AnnotationPointcut {
@Before("execution(* com.flyfly.sp.service.impl.StudentServiceImpl.*(..))")
public void before(){
System.out.println("=================方法执行前==================");
}
@After("execution(* com.flyfly.sp.service.impl.StudentServiceImpl.*(..))")
public void after(){
System.out.println("=================方法执行后=================");
}
}
2、在Spring配置文件中,注册bean,并增加支持注解的配置
<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.flyfly.sp.log.AnnotationPointcut"/>
<!--开启aop注解-->
<aop:aspectj-autoproxy/>
aop:aspectj-autoproxy:说明
通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspect切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了
<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy poxy-target-class=“true”/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。
整合Mybatis
整合所需要的一些准备
<dependencies>
<!--junit包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--Spring操作数据库需要:spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--aop织入包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!--mybatis和spring整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
</dependencies>
<!--配置Maven静态资源过滤问题!-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
MyBatis-Spring学习
MyBatis-Spring 需要以下版本
MyBatis-Spring | MyBatis | Spring 框架 | Spring Batch | Java |
---|---|---|---|---|
2.0 | 3.5+ | 5.0+ | 4.0+ | Java 8+ |
1.3 | 3.4+ | 3.2.2+ | 2.1+ | Java 6+ |
要整合Mybatis必须导入mybatis-spring
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。
在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
注意:SqlSessionFactory 需要一个 DataSource(数据源)。 这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
假设你定义了一个如下的 mapper 接口:
public interface StudentMapper {
List<Student> getAllStu();
}
mapper.xml
<mapper namespace="com.flyfly.mapper.StudentMapper">
<select id="getAllStu" resultType="student">
select * from student
</select>
</mapper>
- 在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory
的。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建。 - 在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession。一旦你获得一个 session之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session。
- SqlSessionFactory有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource
对象,它的配置方法和其它 Spring 数据库连接是一样的。 - 一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis的基础配置非常有用。通常,基础配置指的是 < settings> 或 < typeAliases>元素。
- 需要注意的是,这个配置文件并不需要是一个完整的 MyBatis
配置。确切地说,任何环境配置(),数据源()和 MyBatis的事务管理器()都会被忽略。SqlSessionFactoryBean 会创建它自有的MyBatis 环境配置(Environment),并按要求设置自定义环境的值。 - SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。
- 模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
<?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">
<!--使用spring提供的数据源JDBC替换Mybatis的配置-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myschool?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<!--配置SqlSessionFactory 关联MyBatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="dataSource" ref="datasource"/>
<!--绑定Mybatis配置文件 此时可以不需要MybatisConfig.xml配置文件了,它的配置项可以在这里进行配置-->
<property name="configLocation" value="classpath:Mybatis_config.xml"/>
<property name="mapperLocations" value="classpath:com/flyfly/mapper/*.xml"/>
<property name="typeAliasesPackage" value="com.flyfly.pojo"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入法注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
此时需要比mybatis多写一个mapper的实现类
public class StudentMapperImpl implements StudentMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<Student> getAllStu() {
StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);
List<Student> studentList=mapper.getAllStu();
return studentList;
}
}
并在bean中注入
<bean id="studentMapper" class="com.flyfly.mapper.StudentMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
测试
public class SMTest {
public static void main(String[] args) throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml");
StudentMapper studentMapper=context.getBean("studentMapper",StudentMapper.class);
List<Student> studentList=studentMapper.getAllStu();
for (Student student : studentList) {
System.out.println(student);
}
}
}
整合实现二 mybatis-spring1.2.3版以上的才有这个 .
mapper继承SqlSessionDaoSupport 类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看
public class StudentMapperImpl2 extends SqlSessionDaoSupport implements StudentMapper {
@Override
public List<Student> getAllStu() {
StudentMapper mapper = getSqlSession().getMapper(StudentMapper.class);
//return getSqlSession().getMapper(StudentMapper.class).getAllStu();
return mapper.getAllStu();
}
}
配置bean(可以不要配置SqlSessionTemplate)
<bean id="studentMapper2" class="com.flyfly.mapper.StudentMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
总结 : 整合到spring以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现
事务:声明式事务
事务概要
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
- 事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。
事务四个属性ACID
- 原子性(atomicity)
- 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
- 一致性(consistency)
- 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
- 隔离性(isolation)
- 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
- 持久性(durability)
- 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
Spring中的事务管理
Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。
编程式事务管理
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
使用Spring管理事务,注意头文件的约束导入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器
- 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
- 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。
JDBC事务
<!--jdbc事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource" />
</bean>
配置好事务管理器后我们需要去配置事务的通知
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--propagation默认为REQUIRED;*表示所有方法-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
spring事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
- Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
配置AOP
导入aop的头文件!
<!--AOP织入-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.flyfly.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
如果不配置,就需要我们手动提交控制事务;
事务在项目开发过程非常重要,涉及到数据的一致性的问题,