- 一、什么是Spring
- 二、IOC
- 三、AOP
- 四、事务
- SM整合步骤
- 1)建表
- 2)新建项目,选择quickstart模板
- 3)修改目录
- 4)修改pom.xml文件,添加相关的依赖
- 5)添加MyBatis相应的模板(SqlMapConfig.xml和XXXMapper.xml文件)
- 6)添加SqlMapConfig.xml文件(MyBatis核心配置文件),并拷贝jdbc.propertiest属性文件到resources目录下
- 7)添加applicationContext_mapper.xml
- 8)添加applicationContext_service.xml
- 9)添加Users实体类,Users实体类
- 10)添加mapper包,添加UsersMapper接口和UsersMapper.xml文件并开发
- 11)添加service包,添加UsersService接口和UsersServiceImpl实现类
- 12)添加测试类进行功能测试
- 账户增加一套
- 演示事务
- Spring中事务的五大隔离级别
- Spring事务的传播特性
- SM整合步骤
一、什么是Spring
1.概述
它是一个容器.它是整合其它框架的框架.它的核心是IOC和AOP.它由20多个模块构成.它在很多领域都提供优秀的解决方案.
2.Spring的特点
1)轻量级
由20多个模块构成,每个jar包都很小,小于1M,核心包也就3M左右.
对代码无污染.
2)面向接口编程
使用接口,就是面向灵活,项目的可扩展性,可维护性都极高.接口不关心实现类的类型.使用时接口指向实现类,切换实现类即可切换整个功能.
3)AOP:面向切面编程
就是将公共的,通用的,重复的代码单独开发,在需要的时候反织回去.底层的原理是动态代理.
4)整合其它框架
它整合后使其它框架更易用.
二、IOC
一、概念
3.什么是IOC
控制反转IOC(Inversion of Control)是一个概念,是一种思想。由Spring容器进行对象的创建和依赖注入.程序员在使用时直接取出使用.
正转:由程序员进行对象的创建和依赖注入称为正转.程序员说了算.
Student stu = new Student(); ===>程序员创建对象
stu.setName("张三"); ===>程序员进行赋值
stu.setAge(22);
反转:由Spring容器创建对象和依赖注入称为反转,将控制权从程序员手中夺走,由给Spring容器,称为反转. 容器说了算.
<bean id="stu" class="com.bjpowernode.pojo.Student"> ===>Spring容器负责对象的创建
<property name="name" value="张三"> ===>Spring容器依赖注入值
<property name="age" value="22">
</bean>
切记:Spring容器在启动时,就创建所有的对象stu….
二、基于XML
1.创建对象
1)准备工作
2)引入maven 依赖pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--添加spring的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
3)定义实体类
public class Student {
private String name;
private int age;
//无参,有参
//set() get()
//toString()
}
4)创建Spring的配置文件
<?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">
<!--创建学生对象
等同于 Student stu = new Student();
id:就是创建的对象的名称
class:就是创建的对象的类型,底层通过反射构建对象。
这里只能是类,不能是接口
启动容器的同时,创建对象
-->
<bean id="stu" class="com.bjpowernode.pojo.Student">
</bean>
</beans>
5)创建测试类
public class MyTest {
@Test
public void testStudent(){
//程序员创建对象
// Student stu = new Student();
// System.out.println(stu);
}
@Test
public void testStudentSprng(){
//由spring容器进行对象的创建
//如果想从spring容器中取出对象,则要先创建容器对象,并启动才可以取对象.
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//取出对象
Student stu = (Student) ac.getBean("stu");
System.out.println(stu);
}
}
2.赋值的三种方式
1)setter注入
A简单类型
必须要注意:使用setter注入必须提供无参的构造方法,必须提供setXXX()方法.
<bean id="stu" class="com.bjpowernode.pojo.Student">
<property name="name" value="张三"></property>
<property name="age" value="21"></property>
</bean>
B引用类型
<!--
public class School {
private String name;
private String address;
//...
}
public class Student {
private String name;
private int age;
private School school;
// ..
}
-->
<bean id="school" class="com.bjpowernode.pojo.School">
<property name="name" value="清华大学"></property>
<property name="address" value="海淀区"></property>
</bean>
<bean id="stu" class="com.bjpowernode.pojo2.Student">
<property name="name" value="张三"></property>
<property name="age" value="21"></property>
<property name="school" ref="school"></property>
</bean>
2)通过构造方法注入
使用构造方法参数名称注入值
package com.bjpowernode.pojo3;
/**
*
*/
public class School {
private String name;
private String address;
//使用带参构造方法注入值
public School(String name1, String address1) {
this.name = name1;
this.address = address1;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
<?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="school" class="com.bjpowernode.pojo3.School">
<constructor-arg name="address1" value="海淀区"></constructor-arg>
<constructor-arg name="name1" value="清华大学"></constructor-arg>
</bean>
</beans>
public class MyTest3 {
@Test
public void testSchool(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s03/applicationContext.xml");
School school = (School) ac.getBean("school");
System.out.println(school);
}
//School{name='清华大学', address='海淀区'}
使用构造方法的参数的下标注入值
pojo包
package com.bjpowernode.pojo3;
/**
*
*/
public class School {
private String name;
private String address;
//使用带参构造方法注入值
public School(String name1, String address1) {
this.name = name1;
this.address = address1;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
package com.bjpowernode.pojo3;
/**
*
*/
public class Student {
private String name;
private int age;
//引用类型的成员变量
private School school;
public Student(String name, int age, School school) {
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
<?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="school" class="com.bjpowernode.pojo3.School">
<constructor-arg name="address1" value="海淀区"></constructor-arg>
<constructor-arg name="name1" value="清华大学"></constructor-arg>
</bean>
<!--创建学生对象,使用构造方法的参数的下标注入值-->
<bean id="stu" class="com.bjpowernode.pojo3.Student">
<constructor-arg index="0" value="钱七"></constructor-arg>
<constructor-arg index="2" ref="school"></constructor-arg>
<constructor-arg index="1" value="22"></constructor-arg>
</bean>
</beans>
public class MyTest3 {
@Test
public void testStudent(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s03/applicationContext.xml");
Student stu = (Student) ac.getBean("stu");
System.out.println(stu);
}
}
//Student{name='钱七', age=22, school=School{name='清华大学', address='海淀区'}}
使用构造方法参数默认顺序
<!--创建学生对象,使用默认的构造方法的参数顺序-->
<bean id="stuSequence" class="com.bjpowernode.pojo3.Student">
<constructor-arg value="陈十"></constructor-arg>
<constructor-arg value="22"></constructor-arg>
<constructor-arg ref="school"></constructor-arg>
</bean>
3)引用类型的自动注入
<!--创建学生对象-->
<bean id="stu" class="com.bjpowernode.pojo2.Student" autowire="byName">
<property name="name" value="李四"></property>
<property name="age" value="22"></property>
<!--<property name="school" ref="school"></property>-->
</bean>
<!--创建学校对象-->
<bean id="school" class="com.bjpowernode.pojo2.School">
<property name="name" value="清华大学"></property>
<property name="address" value="海淀区"></property>
</bean>
三、基于注解
基于注解的IOC
也称为DI(Dependency Injection),它是IOC的具体实现的技术.
基于注解的IOC,必须要在Spring的核心配置文件中添加包扫描.
药: 创建对象并依赖注入
汤: xml 注解annotation
1)创建对象的注解
@Component:可以创建任意对象.创建的对象的默认名称是类名的驼峰命名法.也可以指定对象的名称@Component("指定名称").<br /> @Controller:专门用来创建控制器的对象(Servlet),这种对象可以接收用户的请求,可以返回处理结果给客户端.<br /> @Service:专门用来创建业务逻辑层的对象,负责向下访问数据访问层,处理完毕后的结果返回给界面层.<br /> @Repository:专门用来创建数据访问层的对象,负责数据库中的增删改查所有操作.<br />案例:
package com.bjpowernode.s01;
@Component("stu") //交给Spring去创建对象,就是在容器启动时创建
public class Student {
private String name;
private int age;
public Student() {
System.out.println("学生对象的无参构造方法.........");
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--添加包扫描-->
<context:component-scan base-package="com.bjpowernode.s01"></context:component-scan>
</beans>
public class MyTest01 {
@Test
public void testStudent(){
//创建容器对象并启动
ApplicationContext ac = new ClassPathXmlApplicationContext("s01/applicationContext.xml");
//取出对象
Student stu = (Student) ac.getBean("stu");
System.out.println(stu);
}
}
//学生对象的无参构造方法.........
//Student{name='null', age=0}
2)依赖注入的注解
简单类型
简单类型(8种基本类型+String)的注入<br /> @Value:用来给简单类型注入值
@Component("stu") //交给Spring去创建对象,就是在容器启动时创建
public class Student {
@Value("张三") ===>简单类型的值注入
private String name;
@Value("22")
private int age;
...}
引用类型的注入
A.@Autowired:使用类型注入值,从整个Bean工厂中搜索同源类型的对象进行注入.<br /> 同源类型也可注入.<br /> 什么是同源类型:<br /> a.被注入的类型(Student中的school)与注入的类型是完全相同的类型<br /> b.被注入的类型(Student中的school父)与注入的类型(子)是父子类<br /> c.被注入的类型(Student中的school接口)与注入的类型(实现类)是接口和实现类的类型
注意:在有父子类的情况下,使用按类型注入,就意味着有多个可注入的对象.此时按照名称进行二次筛选,选中与被注入对象相同名称的对象进行注入.<br />**引用类型按类型注入**
@Component("schoolNew") //交给srping去创建对象
public class School {
@Value("清华大学")
private String name;
@Value("海淀区")
private String address;
public School() {
System.out.println("School的无参的构造方法.........");
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
@Component
public class Student {
@Value("李四")
private String name;
@Value("23")
private int age;
//引用类型按类型注入
@Autowired
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
引用类型按名称注入
@Component("schoolNew") //交给srping去创建对象
public class School { //此时School对象的名称就是schoolNew
@Value("清华大学")
private String name;
@Value("海淀区")
private String address;
public School() {
System.out.println("School的无参的构造方法.........");
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
@Component
public class Student {
@Value("李四")
private String name;
@Value("23")
private int age;
//引用类型按类型名称注入
@Autowired
@Qualifier("schoolNew")
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
有父类情况下
@Component("schoolFu") //交给srping去创建对象
public class School { //此时School对象的名称就是schoolFu
@Value("清华大学")
private String name;
@Value("海淀区")
private String address;
public School() {
System.out.println("School的无参的构造方法.........");
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
@Component
public class Student {
@Value("李四")
private String name;
@Value("23")
private int age;
//引用类型按类型名称注入
@Autowired
@Qualifier("schoolZi")
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
@Component("schoolZi")
public class SubSchool extends School {
@Value("清华附小")
private String name;
@Value("海淀小区")
private String address;
public SubSchool() {
System.out.println("这是SubSchool子类的构造方法......");
}
@Override
public String toString() {
return "SubSchool{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
三、配置文件拆分
1.添加包扫描的方式
1)单个包扫描(推荐使用)
<context:component-scan base-package="com.bjpowernode.controller"></context:component-scan>
<context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
<context:component-scan base-package="com.bjpowernode.dao"></context:component-scan>
2)多个包扫描,多个包之间以逗号或空格或分号分隔
<context:component-scan base-package="com.bjpowernode.controller com.bjpowernode.service ,com.bjpowernode.dao"></context:component-scan>
3)扫描根包(不推荐)
<context:component-scan base-package="com.bjpowernode"></context:component-scan>
会降低容器启动的速度,导致多做无用功.
2.为应用指定多个 Spring 配置文件
1)拆分配置文件的策略
A.按层拆
applicationContext_controller.xml
<bean id="uController" class="com.bjpowernode.controller.UsersController">
<bean id="bController" class="com.bjpowernode.controller.BookController">
applicationContext_service.xml
<bean id="uService" class="com.bjpowernode.controller.UsersService">
<bean id="bService" class="com.bjpowernode.controller.BookService">
applicationContext_mapper.xml
<bean id="uMapper" class="com.bjpowernode.controller.UsersMapper">
<bean id="bMapper" class="com.bjpowernode.controller.BookMapper">
B.按功能拆
applicationContext_users.xml
<bean id="uController" class="com.bjpowernode.controller.UsersController">
<bean id="uService" class="com.bjpowernode.controller.UsersService">
<bean id="uMapper" class="com.bjpowernode.controller.UsersMapper">
applicationContext_book.xml
<bean id="bController" class="com.bjpowernode.controller.BookController">
<bean id="bService" class="com.bjpowernode.controller.BookService">
<bean id="bMapper" class="com.bjpowernode.controller.BookMapper">
3.spring配置文件的整合
1)单个文件导入
<import resource="applicatoinContext_mapper.xml"></import>
<import resource="applicatoinContext_service.xml"></import>
<import resource="applicatoinContext_controller.xml"></import>
2)批量导入
<import resource="applicatoinContext_*.xml"></import>
三、AOP
1.面向切面编程AOP
AOP(Aspect Orient Programming),面向切面编程。
切面:公共的,通用的,重复的功能称为切面,面向切面编程就是将切面提取出来,单独开发,在需要调用的方法中通过动态代理的方式进行织入.
2.手写AOP框架
业务:图书购买业务
切面:事务
1)第一个版本:业务和切面紧耦合在一起,没有拆分.
2)第二个版本:使用子类代理的方式拆分业务和切面.
3)第三个版本:使用静态代理拆分业务和切面.业务和业务接口已拆分.此时切面紧耦合在业务中.
4)第四个版本:使用静态代理拆分业务和业务接口,切面和切面接口.
5)第五个版本:使用动态代理完成第四个版本的优化.
3.Spring支持的AOP的实现(了解)
Spring支持AOP的编程,常用的有以下几种:
1)Before通知:在目标方法被调用前调用,涉及接口org.springframework.aop.MethodBeforeAdvice;
2)After通知:在目标方法被调用后调用,涉及接口为org.springframework.aop.AfterReturningAdvice;
3)Throws通知:目标方法抛出异常时调用,涉及接口org.springframework.aop.ThrowsAdvice;
4)Around通知:拦截对目标对象方法调用,涉及接口为org.aopalliance.intercept.MethodInterceptor。
4.AOP常用的术语
1)切面:就是那些重复的,公共的,通用的功能称为切面,例如:日志,事务,权限.
2)连接点:就是目标方法.因为在目标方法中要实现目标方法的功能和切面功能.
3)切入点(Pointcut):指定切入的位置,多个连接点构成切入点.切入点可以是一个目标方法,可以是一个类中的所有方法,可以是某个包下的所有类中的方法.
4)目标对象:操作谁,谁就是目标对象.
5)通知(Advice):来指定切入的时机.是在目标方法执行前还是执行后还是出错时,还是环绕目标方法切入切面功能.
Aspect框架
1.AspectJ常见通知类型
AspectJ 中常用的通知有四种类型:
1)前置通知@Before
2)后置通知@AfterReturning
3)环绕通知@Around
4)最终通知@After
5)定义切入点@Pointcut(了解)
2.AspectJ 的切入点表达式(掌握)
规范的公式:
execution(访问权限 方法返回值 方法声明(参数) 异常类型)
简化后的公式:
execution( 方法返回值 方法声明(参数) )
用到的符号:
* 代表任意个任意的字符(通配符)
.. 如果出现在方法的参数中,则代表任意参数
如果出现在路径中,则代表本路径及其所有的子路径
示例:
execution(public (..) ) :任意的公共方法
execution( set(..)) : 任何一个以“set”开始的方法
execution( com.xyz.service.impl..*(..)) :任意的返回值类型,在com.xyz.service.impl包下的任意类的任意方法的任意参数
execution( com.xyz.service...(..)) :任意的返回值类型 ,在com.xyz.service及其子包下的任意类的任意方法的任意参数
例如: com.xyz.service.a.b..(..) com.xyz.service..*(..)
execution( ..service..(..)) :service之前可以有任意的子包
execution( .service..(..)) :service之前只有一个包
Aspect通知
1.AspectJ的前置通知@Before
在目标方法执行前切入切面功能.在切面方法中不可以获得目标方法的返回值,只能得到目标方法的签名.
实现的步骤:
添加依赖
<!--添加spring的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--添加aspectj的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
1)创建业务接口
/**
* 业务接口
*/
public interface SomeService {
String doSome(String name,int age);
void show();
}
2)创建业务实现
/**
* 业务实现类
*/
@Service //这是基于注解的方式添加的
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String name, int age) {
System.out.println("doSome的业务功能实现................");
return "abcd";
}
@Override
public void show() {
System.out.println("show()的业务方法实现执行.............");
}
}
3)创建切面类,实现切面方法
/**
* 此类为切面类,包含各种切面方法
*/
@Aspect //交给AspectJ的框架去识别切面类
@Component
public class MyAspect {
/**
* 所有切面的功能都是由切面方法来实现的
* 可以将各种切面都在此类中进行开发
*
* 前置通知的切面方法的规范
* 1)访问权限是public
* 2)方法的返回值是void
* 3)方法名称自定义
* 4)方法没有参数,如果有也只能是JoinPoint类型
* 5)必须使用@Before注解来声明切入的时机是前切功能和切入点
* 参数:value 指定切入点表达式
*
* 业务方法
* public String doSome(String name, int age)
*/
// @Before(value = "execution(public String com.bjpowernode.s01.SomeServiceImpl.*(String,int))")
// public void myBefore(){
// System.out.println("切面方法中的前置通知功能实现............");
// }
// @Before(value = "execution(public * com.bjpowernode.s01.SomeServiceImpl.*(..))")
// public void myBefore(){
// System.out.println("切面方法中的前置通知功能实现............");
// }
@Before(value = "execution( * com.bjpowernode.s01.*.*(..))")
public void myBefore(JoinPoint jp){
System.out.println("切面方法中的前置通知功能实现............");
System.out.println("目标方法的签名:"+jp.getSignature());
System.out.println("目标方法的参数:"+ Arrays.toString(jp.getArgs()));
}
// @Before(value = "execution( * com.bjpowernode.s01..*(..))")
// public void myBefore(){
// System.out.println("切面方法中的前置通知功能实现............");
// }
// @Before(value = "execution( * *(..))")
// public void myBefore(){
// System.out.println("切面方法中的前置通知功能实现............");
// }
}
4)在applicationContext.xml文件中进行切面绑定
AspectJ框架切换JDK动态代理和CGLib动态代理
记住:使用接口来接,永远不出错.
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--没有基于注解的方式
创建业务对象
<bean id="someService" class="com.bjpowernode.s01.SomeServiceImpl"></bean>
创建切面对象
<bean id="myaspect" class="com.bjpowernode.s01.MyAspect"></bean>
-->
<!--基于注解的访问要添加包扫描-->
<context:component-scan base-package="com.bjpowernode.s01"></context:component-scan>
<!--绑定-->
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
</beans>
public class MyTest01 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s01/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
System.out.println(someService.getClass());
String s = someService.doSome("张三",22);
System.out.println(s);
}
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s01/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
System.out.println(someService.getClass());
someService.show();
}
}
2.@AfterReturning后置通知
后置通知是在目标方法执行后切入切面功能,可以得到目标方法的返回值.如果目标方法的返回值是简单类型(8种基本类型+String)则不可改变.如果目标方法的返回值是引用类型则可以改变.
public class Student {
private String name;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
}
public Student(String name) {
this.name = name;
}
}
public interface SomeService {
String doSome(String name,int age);
Student change();
}
@Service
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String name, int age) {
System.out.println("doSome()业务方法被执行............");
return "abcd";
}
@Override
public Student change() {
System.out.println("change()方法被执行............");
// System.out.println(1/0);
return new Student("张三");
}
}
@Aspect
@Component
public class MyAspect {
/**
* 后置通知的方法的规范
* 1)访问权限是public
* 2)方法没有返回值void
* 3)方法名称自定义
* 4)方法有参数(也可以没有参数,如果目标方法没有返回值,则可以写无参的方法,但一般会写有参,这样可以处理无参可以处理有参),这个切面方法的参数就是目标方法的返回值
* 5)使用@AfterReturning注解表明是后置通知
* 参数:
* value:指定切入点表达式
* returning:指定目标方法的返回值的名称,则名称必须与切面方法的参数名称一致.
*/
@AfterReturning(value = "execution(* com.bjpowernode.s02.*.*(..))",returning = "obj")
public void myAfterReturning(Object obj){
System.out.println("后置通知功能实现..............");
if(obj != null){
if(obj instanceof String){
obj = obj.toString().toUpperCase();
System.out.println("在切面方法中目标方法的返回值:"+obj);
}
if(obj instanceof Student){
Student stu = (Student) obj;
stu.setName("李四");
System.out.println("在切面方法中目标方法的返回值:"+stu);
}
}
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--基于注解的访问要添加包扫描-->
<context:component-scan base-package="com.bjpowernode.s02"></context:component-scan>
<!--绑定-->
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
</beans>
public class MyTest02 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s02/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
String s = someService.doSome("张三",22);
System.out.println("在测试方法中目标方法的返回值:"+s);
}
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s02/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
Student stu = someService.change();
System.out.println("在测试为中目标方法的返回值是:"+stu);
}
}
/*
doSome()业务方法被执行............
后置通知功能实现..............
在切面方法中目标方法的返回值:ABCD
在测试方法中目标方法的返回值:abcd
change()方法被执行............
后置通知功能实现..............
在切面方法中目标方法的返回值:Student{name='李四'}
在测试为中目标方法的返回值是:Student{name='李四'}
*/
3.@环绕通知@Around
它是通过拦截目标方法的方式 ,在目标方法前后增强功能的通知.它是功能最强大的通知,一般事务使用此通知.它可以轻易的改变目标方法的返回值.
public interface SomeService {
String doSome(String name,int age);
}
@Service
public class SomeServiceImpl implements SomeService{
@Override
public String doSome(String name, int age) {
System.out.println("doSome业务方法被执行...."+name);
return "abcd";
}
}
@Aspect
@Component
public class MyAspect {
/**
* 环绕通知方法的规范
* 1)访问权限是public
* 2)切面方法有返回值,此返回值就是目标方法的返回值
* 3)方法名称自定义
* 4)方法有参数,此参数就是目标方法
* 5)回避异常Throwable
* 6)使用@Around注解声明是环绕通知
* 参数:
* value:指定切入点表达式
*/
@Around(value = "execution(* com.bjpowernode.s03.*.*(..))")
public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
//前切功能实现
System.out.println("环绕通知中的前置功能实现............");
//目标方法调用
Object obj = pjp.proceed(pjp.getArgs());
//后切功能实现
System.out.println("环绕通知中的后置功能实现............");
return obj.toString().toUpperCase(); //改变了目标方法的返回值
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--基于注解的访问要添加包扫描-->
<context:component-scan base-package="com.bjpowernode.s03"></context:component-scan>
<!--绑定-->
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
</beans>
public class MyTest03 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s03/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
String s = someService.doSome("张三",22);
System.out.println("在测试方法中目标方法的返回值:"+s);
}
}
/*
环绕通知中的前置功能实现............
doSome业务方法被执行....张三
环绕通知中的后置功能实现............
在测试方法中目标方法的返回值:ABCD
*/
4.最终通知@After
无论目标方法是否正常执行,最终通知的代码都会被执行.
5.给切入点表达式起别名@Pointcut
如果多个切面切入到同一个切入点,可以使用别名简化开发.
使用@Pointcut注解,创建一个空方法,此方法的名称就是别名.
public interface SomeService {
String doSome(String name, int age);
}
@Service
public class SomeServiceImpl implements SomeService {
@Override
public String doSome(String name, int age) {
System.out.println("doSome业务方法被执行...."+name);
//System.out.println(1/0);
return "abcd";
}
}
@Aspect
@Component
public class MyAspect {
/**
* 最终通知方法的规范
* 1)访问权限是public
* 2)方法没有返回值
* 3)方法名称自定义
* 4)方法没有参数,如果有也只能是JoinPoint
* 5)使用@After注解表明是最终通知
* 参数:
* value:指定切入点表达式
*/
@After(value = "mycut()")
public void myAfter(){
System.out.println("最终通知的功能........");
}
@Before(value = "mycut()")
public void myBefore(){
System.out.println("前置通知的功能........");
}
@AfterReturning(value = "mycut()",returning = "obj")
public void myAfterReturning(Object obj){
System.out.println("后置通知的功能........");
}
@Around(value = "mycut()")
public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕通知中的前置通知的功能........");
Object obj = pjp.proceed(pjp.getArgs());
System.out.println("环绕通知中的后置通知的功能........");
return obj;
}
@Pointcut(value = "execution(* com.bjpowernode.s04.*.*(..))")
public void mycut(){}
}
public class MyTest04 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("s04/applicationContext.xml");
//取出代理对象
SomeService someService = (SomeService) ac.getBean("someServiceImpl");
String s = someService.doSome("张三",22);
System.out.println("在测试方法中目标方法的返回值:"+s);
}
}
四、事务
SM整合步骤
注意applicationContext_trans.xml在这里没有使用到,在spring处理两种方式中使用到了。
1)建表
use ssm;
create table users(
userid int primary key,
uname varchar(20),
upass varchar(20)
);
create table accounts(
aid int primary key,
aname varchar(20),
acontent varchar(50)
);
select userid,uname,upass from users;
select aid,aname,acontent from accounts;
delete from users;
delete from accounts;
2)新建项目,选择quickstart模板
3)修改目录
4)修改pom.xml文件,添加相关的依赖
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--aspectj依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--spring核心ioc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--做spring事务用到的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--mybatis和spring集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!--阿里公司的数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
5)添加MyBatis相应的模板(SqlMapConfig.xml和XXXMapper.xml文件)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--读取属性文件中数据库的配置-->
<properties resource="db.properties"></properties>
<!--设置日志输出语句,显示相应操作的sql语名-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.bjpowernode.pojo"></package>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3308/ssm?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="mapper文件所在的包名"></package>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="接口的完全限定名称">
</mapper>
6)添加SqlMapConfig.xml文件(MyBatis核心配置文件),并拷贝jdbc.propertiest属性文件到resources目录下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--读取属性文件中数据库的配置-->
<properties resource="jdbc.properties"></properties>
<!--设置日志输出语句,显示相应操作的sql语名-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.bjpowernode.pojo"></package>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<package name="mapper文件所在的包名"></package>
</mappers>
</configuration>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123
7)添加applicationContext_mapper.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--读取属性文件jdbc.properties-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!--创建数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}456"></property>
</bean>
<!--配置SqlSessionFactoryBean类-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--配置MyBatis的核心配置文件-->
<property name="configLocation" value="SqlMapConfig.xml"></property>
<!--注册实体类的别名-->
<property name="typeAliasesPackage" value="com.bjpowernode.pojo"></property>
</bean>
<!--注册mapper.xml文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bjpowernode.mapper"></property>
</bean>
</beans>
注意:这时候我们需要把SqlMapConfig.xml文件改成这个样子(防止冲突)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--读取属性文件中数据库的配置-->
<!--<properties resource="db.properties"></properties>-->
<!--设置日志输出语句,显示相应操作的sql语名-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--<typeAliases>-->
<!--<package name="com.bjpowernode.pojo"></package>-->
<!--</typeAliases>-->
<!--<environments default="development">-->
<!--<environment id="development">-->
<!--<transactionManager type="JDBC"/>-->
<!--<dataSource type="POOLED">-->
<!--<property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--<property name="url"-->
<!--value="jdbc:mysql://localhost:3308/ssm?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"/>-->
<!--<property name="username" value="root"/>-->
<!--<property name="password" value="123456"/>-->
<!--</dataSource>-->
<!--</environment>-->
<!--</environments>-->
<!--<mappers>-->
<!--<package name="mapper文件所在的包名"></package>-->
<!--</mappers>-->
</configuration>
8)添加applicationContext_service.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"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--SM是基于注解的开发,所以添加包扫描-->
<context:component-scan base-package="com.bjpowernode.service.impl">
</context:component-scan>
</beans>
9)添加Users实体类,Users实体类
public class Users {
private Integer userid;
private String username;
private String upass;
//set() get() toString()
}
10)添加mapper包,添加UsersMapper接口和UsersMapper.xml文件并开发
public interface UsersMapper {
//增加帐户
int insert(Users users);
}
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.UsersMapper">
<!--
int insert(Users users)
实体类:
private Integer userid;
private String username;
private String upass;
-->
<insert id="insert" parameterType="users">
insert into users values(#{userid},#{username},#{upass})
</insert>
</mapper>
11)添加service包,添加UsersService接口和UsersServiceImpl实现类
public interface UsersService {
//增加用户
int insert(Users users);
}
@Service //交给Spring去创建对象
public class UsersServiceImpl implements UsersService {
//切记切记:在所有的业务逻辑层中一定会有数据访问层的对象
/**
* //1.读取核心配置文件
* InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
* //2.创建工厂对象
* SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
* //3.取出sqlSession
* sqlSession = factory.openSession(true);//自动提交事务
* //4.取出动态代理的对象,完成接口中方法的调用,实则是调用xml文件中相的标签的功能
* usersMapper = sqlSession.getMapper(UsersMapper.class);
*/
//在以前我们通过上面的获取usersmapper,我们需要的是数据访问层的功能
//现在我们通过注解,spring帮我们完成注入
/*
MapperScannerConfigurer类已经完成了动态代理的实现
<!--注册mapper.xml文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bjpowernode.mapper"></property>
</bean>
*/
@Autowired
UsersMapper usersMapper;
@Override
public int insert(Users users) {
int num = usersMapper.insert(users);
}
}
12)添加测试类进行功能测试
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--导入applicationContext_mapper.xml文件-->
<import resource="applicationContext_mapper.xml"></import>
<!--SM是基于注解的开发,所以添加包扫描-->
<context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
</beans>
public class MyTest {
@Test
public void testUsers(){
//创建容器并启动
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_service.xml");
//取出UsersServiceImpl
UsersService uService = (UsersService) ac.getBean("usersServiceImpl");
int num = uService.insert(new Users(100,"张三","123"));
System.out.println(num);
}
}
账户增加一套
与上面一共两套业务
public class Accounts {
private Integer aid;
private String aname;
private String acontent;
//set() get() toString()
}
mapper包下
public interface AccountsMapper {
//增加帐户
int save(Accounts accounts);
}
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.AccountsMapper">
<!--
//增加帐户
int save(Accounts accounts);
private Integer aid;
private String aname;
private String acontent;
-->
<insert id="save" parameterType="accounts">
insert into accounts values(#{aid},#{aname},#{acontent})
</insert>
</mapper>
service包下
public interface AccountsService {
int save(Accounts accounts);
}
@Service
public class AccountsServiceImpl implements AccountsService {
//一定会有数据访问层的对象
@Autowired
AccountsMapper accountsMapper;
@Override
public int save(Accounts accounts) {
int num = 0;
num = accountsMapper.save(accounts);
System.out.println("增加帐户成功!num="+num);
return num;
}
}
演示事务
不添加业务
//添加的这个:
手工抛出异常
System.out.println(1/0);
public class AccountsServiceImpl implements AccountsService {
//一定会有数据访问层的对象
@Autowired
AccountsMapper accountsMapper;
@Override
public int save(Accounts accounts) {
int num = 0;
num = accountsMapper.save(accounts);
System.out.println("增加帐户成功!num="+num);
//手工抛出异常
System.out.println(1/0);
return num;
}
}
/*
我们没有添加事务:
账户还是增加成功了
但只是抛出了一个算数异常
*/
添加业务的
基于注解的事务添加步骤
1)在applicationContext_service.xml文件中添加事务管理器
2)在applicationContext_service.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"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--导入applicationContext_mapper.xml文件-->
<import resource="applicationContext_mapper.xml"></import>
<!--SM是基于注解的开发,所以添加包扫描-->
<context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
<!--事务处理-->
<!--1.添加事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--因为事务必须关联数据库处理,所以要配置数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2.添加事务的注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
3)在业务逻辑的实现类上添加注解@Transactional(propagation = Propagation.REQUIRED)
REQUIRED表示增删改操作时必须添加的事务传播特性
@Transactional(propagation = Propagation.REQUIRED)
public class AccountsServiceImpl implements AccountsService {
//一定会有数据访问层的对象
@Autowired
AccountsMapper accountsMapper;
@Override
public int save(Accounts accounts) {
int num = 0;
num = accountsMapper.save(accounts);
System.out.println("增加帐户成功!num="+num);
//手工抛出异常
System.out.println(1/0);
return num;
}
}
/*添加业务以后
账户还是增加失败
抛出了一个算数异常
*/
@Transactional注解参数详解
@Transactional(propagation = Propagation.REQUIRED,//事务的传播特性
noRollbackForClassName = “ArithmeticException”, //指定发生什么异常不回滚,使用的是异常的名称
noRollbackFor = ArithmeticException.class,//指定发生什么异常不回滚,使用的是异常的类型
rollbackForClassName = “”,//指定发生什么异常必须回滚
rollbackFor = ArithmeticException.class,//指定发生什么异常必须回滚
timeout = -1, //连接超时设置,默认值是-1,表示永不超时
readOnly = false, //默认是false,如果是查询操作,必须设置为true.
isolation = Isolation.DEFAULT//使用数据库自已的隔离级别
)
Spring的两种事务处理方式
1)注解式的事务
使用@Transactional注解完成事务控制,此注解可添加到类上,则对类中所有方法执行事务的设定.此注解可添加到方法上,只是对此方法执行事务的处理.
注意:看完事务传播特性在看这个
2)声明式事务(必须掌握),在配置文件中添加一次,整个项目遵循事务的设定.
Spring非常有名的事务处理方式.声明式事务.
要求项目中的方法命名有规范
1)完成增加操作包含 add save insert set
2)更新操作包含 update change modify
3)删除操作包含 delete drop remove clear
4)查询操作包含 select find search get
<?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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--此配置文件与applicationContext_service.xml的功能一样,只是事务配置不同-->
<!--导入applicationContext_mapper.xml-->
<import resource="applicationContext_mapper.xml"></import>
<!--添加包扫描-->
<context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
<!--添加事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务切面-->
<tx:advice id="myadvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*select*" read-only="true"/>
<tx:method name="*find*" read-only="true"/>
<tx:method name="*search*" read-only="true"/>
<tx:method name="*get*" read-only="true"/>
<tx:method name="*insert*" propagation="REQUIRED" no-rollback-for="ArithmeticException"/>
<tx:method name="*add*" propagation="REQUIRED"/>
<tx:method name="*save*" propagation="REQUIRED" no-rollback-for="ArithmeticException"/>
<tx:method name="*set*" propagation="REQUIRED"/>
<tx:method name="*update*" propagation="REQUIRED"/>
<tx:method name="*change*" propagation="REQUIRED"/>
<tx:method name="*modify*" propagation="REQUIRED"/>
<tx:method name="*delete*" propagation="REQUIRED"/>
<tx:method name="*remove*" propagation="REQUIRED"/>
<tx:method name="*drop*" propagation="REQUIRED"/>
<tx:method name="*clear*" propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!--绑定切面和切入点-->
<aop:config>
<aop:pointcut id="mycut" expression="execution(* com.bjpowernode.service.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="myadvice" pointcut-ref="mycut"></aop:advisor>
</aop:config>
</beans>
为什么添加事务管理器
JDBC: Connection con.commit(); con.rollback();
MyBatis: SqlSession sqlSession.commit(); sqlSession.rollback();
Hibernate: Session session.commit(); session.rollback();
事务管理器用来生成相应技术的连接+执行语句的对象.
如果使用MyBatis框架,必须使用DataSourceTransactionManager类完成处理
项目中的所有事务,必须添加到业务逻辑层上.
Spring中事务的五大隔离级别
1).未提交读(Read Uncommitted):允许脏读,也就是可能读取到其他会话中未提交事务修改的数据
2).提交读(Read Committed):只能读取到已经提交的数据。Oracle等多数数据库默认都是该级别 (不重复读)
3).可重复读(Repeated Read):可重复读。在同一个事务内的查询都是事务开始时刻一致的,InnoDB默认级别。在SQL标准中,该隔离级别消除了不可重复读,但是还存在幻象读,但是innoDB解决了幻读
4).串行读(Serializable):完全串行化的读,每次读都需要获得表级共享锁,读写相互都会阻塞
5).使用数据库默认的隔离级别isolation = Isolation.DEFAULT
MySQL:mysql默认的事务处理级别是’REPEATABLE-READ’,也就是可重复读
Oracle:oracle数据库支持READ COMMITTED 和 SERIALIZABLE这两种事务隔离级别。默认系统事务隔离级别是READ COMMITTED,也就是读已提交
Spring事务的传播特性
多个事务之间的合并,互斥等都可以通过设置事务的传播特性来解决.
常用
PROPAGATION_REQUIRED:必被包含事务(增删改必用)
PROPAGATION_REQUIRES_NEW:自己新开事务,不管之前是否有事务
PROPAGATION_SUPPORTS:支持事务,如果加入的方法有事务,则支持事务,如果没有,不单开事务
PROPAGATION_NEVER:不能运行事务中,如果包在事务中,抛异常
PROPAGATION_NOT_SUPPORTED:不支持事务,运行在非事务的环境
不常用
PROPAGATION_MANDATORY:必须包在事务中,没有事务则抛异常
PROPAGATION_NESTED:嵌套事务
为了测试传播特性改造项目
添加的
@Autowired
AccountsService accountsService;
//调用帐户的增加操作,调用的帐户的业务逻辑层的功能
num = accountsService.save(new Accounts(300,”王五”,”帐户好的呢!”));
@Transactional(propagation = Propagation.REQUIRED)
public class AccountsServiceImpl implements AccountsService {
//一定会有数据访问层的对象
@Autowired
AccountsMapper accountsMapper;
@Override
public int save(Accounts accounts) {
int num = 0;
num = accountsMapper.save(accounts);
System.out.println("增加帐户成功!num="+num);
//手工抛出异常
System.out.println(1/0);
return num;
}
}
@Service //交给Spring去创建对象
//@Transactional(propagation = Propagation.REQUIRED)
public class UsersServiceImpl implements UsersService {
//切记切记:在所有的业务逻辑层中一定会有数据访问层的对象
/**
* //1.读取核心配置文件
* InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
* //2.创建工厂对象
* SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
* //3.取出sqlSession
* sqlSession = factory.openSession(true);//自动提交事务
* //4.取出动态代理的对象,完成接口中方法的调用,实则是调用xml文件中相的标签的功能
* uMapper = sqlSession.getMapper(UsersMapper.class);
*/
@Autowired
UsersMapper usersMapper;
@Autowired
AccountsService accountsService;
@Override
public int insert(Users users) {
int num = usersMapper.insert(users);
System.out.println("用户增加成功!num="+num);
//调用帐户的增加操作,调用的帐户的业务逻辑层的功能
num = accountsService.save(new Accounts(300,"王五","帐户好的呢!"));
return num;
}
}