1.Spring整合

1.1 Mybatis

步骤一:数据库表准备
Mybatis是来操作数据库表,所以先创建一个数据库及表

CREATE DATABASE spring_db CHARACTER SET utf8;
USE spring_db;
CREATE TABLE tbl_account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(35),
money DOUBLE
);INSERT INTO tbl_account VALUES(1,"Tom",1000.0);

步骤二:创建项目导入jar包
项目的pol.xml添加相关依赖

    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency></dependencies>

步骤3:根据表创建模型类

package com.example.poji;import java.io.Serializable;public class Account implements Serializable {private Integer id;private String name;private Double money;public Account() {}public Account(Integer id, String name, Double money) {this.id = id;this.name = name;this.money = money;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}

步骤4:创建Dao接口

package com.example.dao;import com.example.poji.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import java.util.List;public interface AccountDao {@Insert("insert into tbl_account(name,money)values(#{name},#{money})")void save(Account account);@Delete("delete from tbl_account where id = #{id} ")void delete(Integer id);@Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")void update(Account account);@Select("select * from tbl_account")List<Account> findAll();@Select("select * from tbl_account where id = #{id} ")Account findById(Integer id);
}

步骤5:创建Service接口和实现类

package com.example.service;import com.example.poji.Account;import java.util.List;public interface AccountService {void save(Account account);void delete(Integer id);void update(Account account);List<Account> findAll();Account findById(Integer id);
}package com.example.service.impl;import com.example.dao.AccountDao;
import com.example.poji.Account;
import com.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;public void save(Account account) {accountDao.save(account);}public void update(Account account){accountDao.update(account);}public void delete(Integer id) {accountDao.delete(id);}public Account findById(Integer id) {return accountDao.findById(id);}public List<Account> findAll() {return accountDao.findAll();}
}

步骤6:添加jdbc.properties文件
resources目录下添加,用于配置数据库连接四要素

jdbc.driver=com.mysql.jc.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.224:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=123456

步骤7:添加Mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--读取外部properties配置文件--><properties resource="jdbc.properties"></properties><!--别名扫描的包路径--><typeAliases><package name="com.example.poji"/></typeAliases><!--数据源--><environments default="mysql"><environment id="mysql"><transactionManager type="JDBC"></transactionManager><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="com.example.dao"></package></mappers>
</configuration>

步骤8:编写应用程序

package com.example;import com.example.dao.AccountDao;
import com.example.poji.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class App {public static void main(String[] args) throws IOException {// 1. 创建SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();// 2. 加载SqlMapConfig.xml配置文件InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");// 3. 创建SqlSessionFactory对象SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);// 4. 获取SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 5. 执行SqlSession对象执行查询,获取结果UserAccountDao accountDao = sqlSession.getMapper(AccountDao.class);Account ac = accountDao.findById(1);System.out.println(ac);// 6. 释放资源sqlSession.close();}
}

步骤9:运行程序
Account{id=1, name=‘Tom’, money=1000.0}

1.2 Spring整合MyBatis

思路分析

//初始化SqlSessionFactory
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//获取连接,获取实现
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取数据层接口
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
Account ac = accountDao.findById(1);
System.out.println(ac);
// 关闭连接
sqlSession.close();

sqlSessionFactory是核心对象

<configuration><!--初始化属性数据--><properties resource="jdbc.properties"></properties><!--初始化数据别名--><typeAliases><package name="com.example.poji"/></typeAliases><!--初始化dataSource--><environments default="mysql"><environment id="mysql"><transactionManager type="JDBC"></transactionManager><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="com.example.dao"></package></mappers>
</configuration>

实验

① 导入坐标

<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.10.RELEASE</version>
</dependency>
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version>
</dependency>

② 添加配置(SpringConfig、JdbcConfig、MybatisConfig)

package com.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;@Configuration
@ComponentScan("com.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {}package com.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String drive;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(drive);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}
}package com.example.config;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("com.example.poji");ssfb.setDataSource(dataSource);return ssfb;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.example.dao");return msc;}
}

③ 测试

package com.example;import com.example.config.SpringConfig;
import com.example.poji.Account;
import com.example.service.AccountService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App2 {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);AccountService accountService = ctx.getBean(AccountService.class);Account ac = accountService.findById(1);System.out.println(ac);}
}

1.3 Spring整合JUnit

① 导入坐标

<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.10.RELEASE</version>
</dependency>

② 在src.main.test.java包下创建测试类

import com.example.config.SpringConfig;
import com.example.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testFindById(){System.out.println(accountService.findById(1));}
}

2.AOP

2.1 AOP简介

AOP(Aspect Oriented Programming)面向切面编程,一种编程范式,知道开发者如何组织程序结构
  OOP(Object Oriented Programming)面向对象编程

作用:在不惊动原始设计的基础上为其进行功能增强
Spring理念:无入侵式/无侵入式

AOP核心概念

  1. 连接点(JoinPoint):程序执行过程中的任意位置,粒度为执行方法、抛出异常、设置变量等

    • 在SpringAOP中,理解为方法的执行
  2. 切入点(Pointcut):匹配连接点的式子
    • 在SpringAOP中,一个切入点可以描述一个具体方法,也可也匹配多个方法

      • 一个具体的方法:如com.example.dao包下的BookDao接口中的无形参无返回值的save方法
      • 匹配多个方法:所有的save方法,所有的get开头的方法,所有以Dao结尾的接口中的任意方法,所有带有一个参数的方法
    • 连接点范围要比切入点范围大,是切入点的方法也一定是连接点,但是是连接点的方法就不一定要被增强,所以可能不是切入点。
  3. 通知(Advice):在切入点处执行的操作,也就是共性功能
    • 在SpringAOP中,功能最终以方法的形式呈现
  4. 通知类:定义通知的类
  5. 切面(Aspect):描述通知与切入点的对应关系。

2.2 AOP入门案例

案例:在接口执行前输出当前系统时间

思路分析:
1.导入坐标(pon.xml)
2.连接点方法(原始操作,Dao接口与实现类)
3.制作共性功能(通知类与通知)
4.定义切入点
5.绑定切入点与通知关系(切面)

初始环境
BookDao接口

package com.example.dao;public interface BookDao {public void save();public void update();
}

BookDaoImpl实现类

package com.example.dao.impl;import com.example.dao.BookDao;
import org.springframework.stereotype.Repository;@Repository
public class BookDaoImpl implements BookDao {public void save() {System.out.println(System.currentTimeMillis());System.out.println("book dao save ..." );}public void update() {System.out.println("book dao update ...");}}

SpringConfig核心配置文件

package com.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan("com.example")
public class SpringConfig {}

App运行类

package com.example;import com.example.config.SpringConfig;
import com.example.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);bookDao.save();bookDao.update();}
}

实验步骤:
① 添加坐标

<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version>
</dependency>

② 通知类

package com.example.aop;import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;@Component
@Aspect
public class MyAdvice {//定义切入点//说明:切入点定义依托一个不具有实际意义的方法进行,即无参数无返回值,方法体无实际逻辑@Pointcut("execution(void com.example.dao.BookDao.update())")private void pt(){}//绑定切入点和通知@Before("pt()")//定义通知public void method(){System.out.println(System.currentTimeMillis());}
}

③ 修改核心配置

package com.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class SpringConfig {}

2.3 AOP工作流程

1.Spring容器启动
2.读取所有切面配置的切入点
3.初始化bean,判定bean对应的类中方法是否匹配到任意切入点
匹配失败,创建对象
匹配成功,创建原始对象(目标对象)的代理对象

4.获取bean执行方法
获取bean,调用方法并执行,完成操作
获取bean是代理对象时,根据对象的运行模式运行原始方法与增强的内容,完成操作

AOP核心概念
目标对象(Target):原始功能去掉共性功能对应的类产生的对象,这种对象是无法直接完成最终工作的
代理(Proxy):目标对象无法直接完成工作,需要对其进行功能回填,通过原始对象的代理对象实现

SpringAOP本质:代理模式

2.4 AOP切入点表达式

切入点:要进行增强的方法
切入点表达式:要进行增强的方法的描述方式

描述方式一:执行com.example.dao包下的BookDao接口中的无参数update方法
execution(void com.example.dao.BookDao.update())

描述方式二:执行com.example.dao.impl包下的BookDaoImpl类中的无参数update方法
execution(void com.example.dao.impl.BookDaoImpl.update())

切入点表达式
动作关键字 (访问修饰符 返回值 包名.类/接口.方法 (参数)异常名)

execution(public User com.example.service.UserService.findById (int))

动作关键字:描述切入点的行为动作,例如execution表示执行到指定切入点
访问修饰符:public,private等,可以省略
返回值
包名
类/接口
方法名
参数
异常名:方法定义中抛出指定异常,可以省略

可以使用通配符描述切入点,快速描述

    • :单个独立的任意符号,可以独立出现,也可以作为前缀或后缀的匹配符出现
execution(public * com.example.*.UserService.find* (*))

匹配com.example包下的任意包中的UserService类或接口中所有find开头的带有一个参数的方法

  1. … :多个连续的任意符号,可以独立出现,常用于简化包名与参数的书写
execution(punlic User Com..UserService.findById (..))

匹配com包下的任意包中的UserService类或接口中所有名称为findById的方法

    • :专用于匹配子类类型
exection(* *..*Service+.*(..))

书写技巧

  • 所有代码按照标准规范开发,否则以下技巧全部失效
  • 描述切入点通常描述接口,而不描述实现类,如果描述到实现类,就出现紧耦合了
  • 访问控制修饰符针对接口开发均采用public描述(可省略访问控制修饰符描述)
  • 返回值类型对于增删改类使用精准类型加速匹配,对于查询类使用*通配快速描述
  • 包名书写尽量不使用…匹配,效率过低,常用*做单个包描述匹配,或精准匹配
  • 接口名/类名书写名称与模块相关的采用匹配,例如UserService书写成Service,绑定业务层接口名
  • 方法名书写以动词进行精准匹配,名词采用匹配,例如getById书写成getBy,selectAll书写成selectAll
  • 参数规则较为复杂,根据业务方法灵活调整
  • 通常不使用异常作为匹配规则

2.5 AOP通知类型

AOP通知描述了抽取的共性功能,根据共性功能抽取的位置不同,最终运行代码时要将其加入到合理的位置
AOP通知共分5种类型
1.前置通知(@Before)
2.后置通知(@After)
3.环绕通知(重点 @Around)
4.返回后通知(了解 @AfterReturning)
5.抛出异常后通知(了解 @AfterThrowing)

@Around注意事项

  1. 环绕通知必须依赖形参ProceedingJoinPoint才能实现对原始方法的调用,进而实现原始方法调用前后同时添加通知
  2. 通知中如果未使用ProceedingJoinPoint对原始方法进行调用将跳过原始方法的执行
  3. 对原始方法的调用可以不接收返回值,通知方法设置成void即可,如果接收返回值,最好设定为Object类型
  4. 原始方法的返回值如果是void类型,通知方法的返回值类型可以设置成void,也可以设置成Object
  5. 由于无法预知原始方法运行后是否会抛出异常,因此环绕通知方法必须要处理Throwable异常

实验

package com.example.aop;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Component
@Aspect
public class MyAdvice {@Pointcut("execution(void com.example.dao.BookDao.update())")private void pt(){}@Before("pt()")public void before(){System.out.println("before advice...");}@After("pt()")public void after(){System.out.println("after advice...");}@Around("pt()")public Object round(ProceedingJoinPoint pjp) throws Throwable {System.out.println("round before advice...");//表示对原始操作的调用Object ret = pjp.proceed();System.out.println("round after advice...");return ret;}@AfterReturning("pt()")public void afterReturning(){System.out.println("afterReturning advice...");}@AfterThrowing("pt()")public void afterThrowing(){System.out.println("afterThrowing advice...");}
}

2.6 案例:册产量业务层接口万次执行效率

需求:任意业务层接口执行均可显示器执行效率(执行时长)
分析:
① 业务工鞥:业务层接口执行之前分别记录时间,求差值得到执行效率
② 通知类型选择前后均可增强的类型——环绕通知

第一步:核心配置

package com.example.config;import org.springframework.context.annotation.*;@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {}

第二步:通知类

package com.example.aop;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;@Component
@Aspect
public class ProjectAdvice {//匹配业务层的所有方法@Pointcut("execution(* com.example.service.*Service.*(..))")private void servicePt(){}@Around("ProjectAdvice.servicePt()")public void runSpeed(ProceedingJoinPoint pjp) throws Throwable {Signature signature = pjp.getSignature();String className = signature.getDeclaringTypeName();String methodName = signature.getName();long start = System.currentTimeMillis();for(int i = 0;i < 1000;i++){pjp.proceed();}long end = System.currentTimeMillis();System.out.println("万次执行:" +className + "." + methodName + "---->"+ (end-start) + "ms");}
}

第三步:测试

import com.example.config.SpringConfig;
import com.example.poji.Account;
import com.example.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testFindById(){accountService.findById(1);}@Testpublic void testFindAll(){List<Account> all = accountService.findAll();}
}

结果

万次执行:com.example.service.AccountService.findAll---->2196ms
万次执行:com.example.service.AccountService.findById---->253ms

补充说明:当前测试的接口效率仅仅是一个理论值,并不是一次完整执行的过程

2.7 AOP通知获取数据

  1. 获取切入点方法的参数

    • JoinPoint:适用于前置、后置、返回后、抛出异常后通知
    • ProceedJoinPoint:适用于环绕通知
  2. 获取切入点方法返回值
    • 返回后通知
    • 环绕通知
  3. 获取切入点方法运行异常信息
    • 抛出异常后通知
    • 环绕通知

实验
核心配置

package com.example.config;import org.springframework.context.annotation.*;@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class SpringConfig {}

BookDao接口

package com.example.dao;public interface BookDao {public String findName(int id,String password);
}

BookDaoImpl实现类

package com.example.dao.impl;import com.example.dao.BookDao;
import org.springframework.stereotype.Repository;@Repository
public class BookDaoImpl implements BookDao {public String findName(int id,String password) {System.out.println("id:"+id);return "itcast";}
}

App运行类

package com.example;import com.example.config.SpringConfig;
import com.example.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);String name = bookDao.findName(100,"test");System.out.println(name);}
}

通知类

package com.example.aop;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.Arrays;@Component
@Aspect
public class MyAdvice {@Pointcut("execution(* com.example.dao.BookDao.findName(..))")private void pt(){}@Before("pt()")public void before(JoinPoint jp){Object[] args = jp.getArgs();System.out.println(Arrays.toString(args));System.out.println("before advice...");}@After("pt()")public void after(JoinPoint jp){Object[] args = jp.getArgs();System.out.println(Arrays.toString(args));System.out.println("after advice...");}@Around("pt()")public Object round(ProceedingJoinPoint pjp){Object[] args = pjp.getArgs();System.out.println(Arrays.toString(args));args[0] = 666;Object ret = null;try {ret = pjp.proceed(args);} catch (Throwable e) {throw new RuntimeException(e);}return ret;}//如果有JoinPoint jp参数,必须放在第一位@AfterReturning(value = "pt()",returning = "ret")public void afterReturning(Object ret){System.out.println("afterReturning advice..."+ret);}@AfterThrowing(value = "pt()",throwing = "t")public void afterThrowing(Throwable t){System.out.println("afterThrowing advice...");}
}

2.8 案例:百度网盘数据兼容处理

需求:对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理
分析:
① 在业务方法执行之前对所有的输入参数进行格式化——trim()
② 使用处理后的参数调用原始方法——环绕通知中存在对原始方法的调用

配置准备
ResourcesService接口

package com.example.service;public interface ResourcesService {public boolean openURL(String url,String password);
}

ResourcesServiceImpl实现类

package com.example.service.impl;import com.example.dao.ResourcesDao;
import com.example.service.ResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class ResourcesServiceImpl implements ResourcesService {@Autowiredprivate ResourcesDao resourcesDao;public boolean openURL(String url, String password) {return resourcesDao.readResources(url,password);}
}

ResourcesDao接口

package com.example.dao;public interface ResourcesDao {boolean readResources(String url,String password);
}

ResourcesDaoImpl实现类

package com.example.dao.impl;import com.example.dao.ResourcesDao;
import org.springframework.stereotype.Repository;@Repository
public class ResourcesDaoImpl implements ResourcesDao {public boolean readResources(String url, String password) {//模拟校验return password.equals("root");}
}

App运行类

package com.example;import com.example.config.SpringConfig;
import com.example.service.ResourcesService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);ResourcesService resourcesService = ctx.getBean(ResourcesService.class);boolean flag = resourcesService.openURL("WWW://pan.baidu.com/www", "root");System.out.println(flag);}
}

实验
开启AOP注解

package com.example.config;import org.springframework.context.annotation.*;@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class SpringConfig {}

通知类(去除密码前后的空格)

package com.example.aop;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;@Component
@Aspect
public class DataAdvice {@Pointcut("execution(boolean com.example.service.ResourcesService.openURL(*,*))")private void servicePt(){}@Around("DataAdvice.servicePt()")public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {Object[] args = pjp.getArgs();for(int i = 0;i < args.length;i++){//判断参数是不是字符串if(args[i].getClass().equals(String.class)){args[i] = args[i].toString().trim();}}Object ret = pjp.proceed(args);return ret;}
}

在App中传入密码前后加空格测试结果仍然为true

3.Spring事务

3.1 Spring事务简介

事务作用:在数据层保障一系列的数据库操作同成功同失败
Spring事务作用:在数据层或业务层保障一系列的数据库操作同成功同失败

3.2 案例:银行账户转账

需求:实现任意两个账户转账操作
需求微缩: A账户减钱,B账户加钱

分析:
① 数据层提供基础操作,指定账户减钱(outMoney),指定账户加钱(inMoney)
② 业务层提供转账操作(transfer),调用减钱与加钱的操作
③ 提供2个账号和操作金额执行转账操作
④ 提供2个账号和操作金额执行转账操作

环境准备
数据库包含的数据

mysql> select * from tbl_account;
+----+-------+-------+
| id | name  | money |
+----+-------+-------+
|  1 | Tom   |  1000 |
|  2 | Jerry |  1000 |
+----+-------+-------+
2 rows in set (0.00 sec)

AccountDao接口(实现对数据库的操作)

package com.example.dao;import org.apache.ibatis.annotations.*;public interface AccountDao {@Update("update tbl_account set money = money + #{money} where name = #{name}")void inMoney(@Param("name") String name,@Param("money") Double money);@Update("update tbl_account set money = money - #{money} where name = #{name}")void outMoney(@Param("name") String name,@Param("money") Double money);
}

AccountService接口

package com.example.service;public interface AccountService {public void transfer(String out,String in,Double money);
}

AccountService实现类

package com.example.service.impl;import com.example.dao.AccountDao;
import com.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;public void transfer(String out, String in, Double money) {accountDao.outMoney(out,money);accountDao.inMoney(in,money);}
}

核心配置

package com.example.config;import org.springframework.context.annotation.*;@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {}

测试类

import com.example.config.SpringConfig;
import com.example.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testTransfer(){accountService.transfer("Tom","Jerry",100D);}
}

实验

① 在业务层接口上添加Spring事务管理

package com.example.service;import org.springframework.transaction.annotation.Transactional;public interface AccountService {@Transactionalpublic void transfer(String out,String in,Double money);
}

注意事项:Spring注解式事务通常添加在业务层接口中而不会添加到业务层实现类中,降低耦合
注解式事务可以添加到业务方法上表示当前方法开启事务,也可以添加到接口上表示当前接口所有方法开启事务

② 设置事务管理器(JdbcConfig中)

@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();transactionManager.setDataSource(dataSource);return transactionManager;
}

注意事项:事务管理器要根据实现技术进行选择
MyBatis框架使用的是JDBC事务

③ 开启注解式事务驱动
@EnableTransactionManagement

package com.example.config;import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
@ComponentScan("com.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {}

④ 测试
AccountServiceImpl中添加异常报错

public void transfer(String out, String in, Double money) {accountDao.outMoney(out,money);int i = 1 / 0;accountDao.inMoney(in,money);
}

进行测试,观察报错后是否回滚事务

3.3 Spring事务角色

事务角色:
事务管理员:发起事务方,在Spring中通常指代业务层开启事务的方法
事务协调员:加入事务方,在Spring中通常指代数据层方法,也可以是业务层方法

3.4 事务相关配置

属性 作用 示例
readOnly 设置是否为只读事务 readOnly=true 只读事务
timeout 设置事务超时时间 timeout = -1 (永不超时)
rollbackFor 设置事务回滚异常(class) rollbackFor = (NullPointException.class)
rollbackForClassName 设置事务回滚异常(String) 同上格式为字符串
noRollbackFor 设置事务不回滚异常(class) noRollbackFor = (NullPointException.class)
noRollbackForClassName 设置事务不回滚异常(String) 同上格式为字符串
propagation 设置事务传播行为

举例

@Transactional(timeout = -1,rollbackFor = {IOException.class})

案例:转账业务追加日志
需求:实现任意两个账户间转账操作,并对每次转账操作在数据库进行留痕
需求微缩:A账户减钱,B账户加钱,数据库记录日志

分析:
① 基于转账操作案例添加日志模块,实现数据库中记录日志
② 业务层转账操作(transfer),调用减钱、加钱与记录日志功能

预期效果为:
无论转账操作是否成功,均进行转账操作的日志留痕

事务传播行为:事务协调员对事务管理员所携带事务的处理态度

实验
① 创建日志表

create table tbl_log(id int primary key auto_increment,info varchar(255),createDate datetime
)

② 添加LogDao接口

package com.example.dao;import org.apache.ibatis.annotations.Insert;public interface LogDao {@Insert("insert into tbl_log (info,createDate) values(#{info},now())")void log(String info);
}

③ 添加LogService接口与实现类

package com.example.service;public interface LogService {@Transactionalvoid log(String out, String in, Double money);
}package com.example.service.impl;import com.example.dao.LogDao;
import com.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;@Service
public class LogServiceImpl implements LogService {@Autowiredprivate LogDao logDao;public void log(String out,String in,Double money ) {logDao.log("转账操作由"+out+"到"+in+",金额:"+money);}
}

④ 在转账的业务中添加记录日志

package com.example.service.impl;import com.example.dao.AccountDao;
import com.example.service.AccountService;
import com.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Autowiredprivate LogService logService;public void transfer(String out, String in, Double money) {try {accountDao.outMoney(out,money);int i = 1 / 0;accountDao.inMoney(in,money);}finally {logService.log(out,in,money);}}
}

测试发现没有实现需求的效果
失败原因:日志的记录与转账操作隶属同一个事务,同成功同失败

事务传播行为:事务协调员对事务管理员所携带事务的处理态度。

⑤ 在业务层接口上添加Spring事务,何止事务的传播行为REQUIRES_NEW(需要新事物)
LogService接口中

@Transactional(propagation = Propagation.REQUIRES_NEW)

2.SSM之Spring整合、AOP及Spring事务相关推荐

  1. SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

    登录 | 注册 收藏成功 确定 收藏失败,请重新收藏 确定 查看所有私信查看所有通知 暂没有新通知 想要绕过微信小程序开发中的坑吗?不妨来听这个,今晚8点,1小时帮你搞定! 14小时以前 CSDN日报 ...

  2. 解决在Spring整合Hibernate配置tx事务管理器出现错误的问题

    解决在Spring整合Hibernate配置tx事务管理器出现错误的问题 参考文章: (1)解决在Spring整合Hibernate配置tx事务管理器出现错误的问题 (2)https://www.cn ...

  3. Spring(四)——AOP、Spring实现AOP、Spring整合Mybatis、Spring中的事务管理

    文章目录 1. 什么是AOP 2. 使用Spring实现AOP 2.1 使用Spring的API 接口实现 2.2 自定义实现 2.3 使用注解实现 3. 整合MyBatis 3.1 MyBatis- ...

  4. 通俗易懂-SSM三大框架整合案例(SpringMVC+Spring+Mybatis)

    前言: 学习B站UP狂神说视频笔记整理视频链接 相关代码已经上传至码云:码云链接 前期准备 项目介绍 demo项目是一个简单的图书管理系统,主要功能为表单数据的增删改查 Web端使用JSP+Boots ...

  5. [转]SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

    使用SSM(spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录SSM整合 ...

  6. SSM框架详细整合教程(Spring+SpringMVC+MyBatis)

    动机 使用maven已经有一段时间了,但项目是别人搭建好的,因此一直想着自己要学习搭建一下.网上找了些资料后,结合自己实验,花了点时间就搞好,老样子,写在博客上,免得日后忘记. 本文链接:http:/ ...

  7. spring整合atomikos实现分布式事务的方法示例_分布式-分布式事务处理

    在之前的文章"如何合理的使用动态数据源"中,其实也提到了分布式事务相关的场景如:利用多数据源实现读写分离,但直接使用动态数据源频繁其实是很消耗资源的,而且就是当业务service一 ...

  8. spring整合atomikos实现分布式事务的方法示例_分布式事务一:基于数据库原生分布式事务方案实现...

    1.分布式事务模型 ACID 实现 1.1.X/Open XA 协议(XA) 最早的分布式事务模型是 X/Open 国际联盟提出的 X/Open Distributed Transaction Pro ...

  9. spring整合atomikos实现分布式事务的方法示例_分布式事务中的XA和JTA

    在介绍这两个概念之前,我们先看看是什么是X/Open DTP模型. X/Open X/Open,即现在的open group,是一个独立的组织,主要负责制定各种行业技术标准.X/Open组织主要由各大 ...

  10. SSM整合第二步之Spring

    目录 Spring整合Mybatis Spring整合Service层 Spring整合Mybatis 新建spring-dao.xml配置文件 <?xml version="1.0& ...

最新文章

  1. nestjs连接远程mysql_Nestjs 链接mysql
  2. python实例属性与类属性_Python中的类属性和实例属性引发的一个坑-续
  3. 愿你白天有说有笑,晚上睡个好觉
  4. LeetCode 2114. 句子中的最多单词数
  5. python pdb调试基本命令整理
  6. 信息学奥赛一本通(2057:【例3.9 】星期几)
  7. CVPR 2021 接收论文临时列表!27%接受率!
  8. mysql数据库的远程访问_mysql数据库远程访问设置方法
  9. linux进程阻塞的原因,释放大块内存时的阻塞问题
  10. 软路由初次尝试者的折腾指南
  11. 注册表改win 7更新服务器,uefi安装win7卡在更新注册表设置解决新方法(完美解决)...
  12. 北京大学数学科学学院2006\9\20声明:坚持真理、追求卓越zz
  13. python象棋博弈算法_python做中国国粹——象棋
  14. 2.4G蓝牙耳机等穿戴蓝牙设备贴片天线方案 CA-C01
  15. Android Studio开发(四)SQLite数据库的DAO标准CRUD操作模拟微信通讯录
  16. 如何查看当前分支从哪个支线创建而来
  17. (RN)Region Normalization for Image Inpainting
  18. vmware exis如何设置双网卡
  19. 长途枢纽大楼综合布线系统
  20. Unity3D人物角色描边、模型描边

热门文章

  1. linux应用/软件设置为系统服务
  2. 中职计算机应用教学的重要性,中职《计算机应用基础》教学中理实一体化的有效开展...
  3. 数据挖掘并不遥远( 转载)
  4. mini2440+阿里云+Qt/android 打造智能音箱
  5. 福昕PDF不可编辑解决方法
  6. 怒江java培训班_Graal VM:微服务时代的Java
  7. CAD如何使用圆命令做辅助线绘制梯形图案呢?
  8. win10常见问题-任务栏消失
  9. item_password-获得1688平台淘口令真实url,1688短链接搜索商品接口接入解决方案
  10. 信息安全人员关注网站