AOP术语

名词 解释
Joinpoint 连接点 可以用于把增强代码加入到业务主线中的点。
这些点指的就是方法,在方法执行的前后通过动态代理技术加入增强的代码。
在Spring框架AOP思想的技术实现中,也只支持方法类型的Joinpoint。
Pointcut 切入点 已经把增强代码加入到业务主线进来之后的连接点。
Advice 通知/增强 切面类中用于提供增强功能的方法,且不同的方法增强的时机是不一样的。
如,开启事务肯定要在业务方法执行之前执行,提交事务要在业务方法正常执行之后执行,回滚事务要在业务方法执行产生异常之后执行。
分类:
- 前置通知 - aop:before
- 最终通知 - aop:after
- 环绕通知 - aop:around
- 正常执行通知 - aop:after-returning
- 异常执行通知 - aop:after-throwing
Target 目标对象 代理的目标对象,即被代理对象。
Proxy 代理 一个类被AOP织入增强后产生的代理类,即代理对象。
Weaving 织入 把增强应用到目标对象来创建新的代理对象的过程。
Spring采用动态代理织入,AspectJ采用编译期织入和类装载期织入。
Aspect 切面 增强的代码所关注的方法,把这些相关的增强代码定义到一个类中,这个类就是切面类。
如,事务切面,里面定义的方法就是和事务相关的,比如开始事务、提交事务、回滚事务。

Spring AOP的三种模式

纯xml模式

一个demo:

  1. <!--
  2. Spring基于XML的AOP配置前期准备:
  3. 在spring的配置文件中加入aop的约束
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. http://www.springframework.org/schema/aop
  6. https://www.springframework.org/schema/aop/spring-aop.xsd
  7. Spring基于XML的AOP配置步骤:
  8. 第一步:把通知Bean交给Spring管理
  9. 第二步:使用aop:config开始aop的配置
  10. 第三步:使用aop:aspect配置切面
  11. 第四步:使用对应的标签配置通知的类型
  12. 入⻔案例采用前置通知,标签为aop:before
  13. -->
  14. <!--把通知bean交给spring来管理-->
  15. <bean id="logUtil" class="com.lagou.utils.LogUtil"></bean>
  16. <!--开始aop的配置-->
  17. <aop:config>
  18. <!--配置切面-->
  19. <aop:aspect id="logAdvice" ref="logUtil">
  20. <!--配置前置通知-->
  21. <aop:before method="printLog" pointcut="execution(public * com.lagou.service.impl.TransferServiceImpl.updateAccountByCardNo(com.lagou.pojo.Account))" />
  22. </aop:aspect>
  23. </aop:config>

xml+注解模式

需要在xml里开启Spring对注解AOP的支持:

<!--开启spring对注解aop的支持-->
<aop:aspectj-autoproxy/>

一个demo:


/**
 * 模拟记录日志 * @author 应癫 */
@Component
@Aspect
public class LogUtil {
    /**
     * 我们在xml中已经使用了通用切入点表达式,供多个切面使用,那么在注解中如何使用呢?
     * 第一步:编写一个方法
     * 第二步:在方法使用@Pointcut注解
     * 第三步:给注解的value属性提供切入点表达式
     * 细节:
     * 1.在引用切入点表达式时,必须是方法名+(),例如"pointcut()"。
     * 2.在当前切面中使用,可以直接写方法名。在其他切面中使用必须是全限定方法名。
     */
    @Pointcut("execution(* com.lagou.service.impl.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void beforePrintLog(JoinPoint jp) {
        Object[] args = jp.getArgs();
        System.out.println("前置通知:beforePrintLog,参数是:" + Arrays.toString(args));
    }

    @AfterReturning(value = "pointcut()", returning = "rtValue")
    public void afterReturningPrintLog(Object rtValue) {
        System.out.println("后置通知:afterReturningPrintLog,返回值 是:" + rtValue);
    }

    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowingPrintLog(Throwable e) {
        System.out.println("异常通知:afterThrowingPrintLog,异常是:" + e);
    }

    @After("pointcut()")
    public void afterPrintLog() {
        System.out.println("最终通知:afterPrintLog");
    }

    /**
     * 环绕通知
     *
     * @param pjp * @return
     */
    @Around("pointcut()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        //定义返回值
        Object rtValue = null;
        try {
            //前置通知 System.out.println("前置通知");
            //1.获取参数
            Object[] args = pjp.getArgs();


            //2.执行切入点方法
            rtValue = pjp.proceed(args);
            //后置通知
            System.out.println("后置通知");
        } catch (Throwable t) {
            //异常通知
            System.out.println("异常通知"); t.printStackTrace();
        } finally { //最终通知
            System.out.println("最终通知");
        }
        return rtValue;
    }
}

注解模式

把:

<!--开启spring对注解aop的支持-->
<aop:aspectj-autoproxy/>

替换为:

/**
 * @author 应癫 
 */
@Configuration
@ComponentScan("com.lagou")
@EnableAspectJAutoProxy //开启spring对注解AOP的支持 
public class SpringConfiguration {
}

即可。

Spring声明式事务的支持

事务

事务指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部不成功,从而确保数据的准确与安全。

事务的四大特性

  • 原子性(Atomicity)
  • 一致性(Consistency)
  • 隔离性(Isolation)
  • 持久性(Durability)

事务的隔离级别

如果不考虑事务的隔离级别,可能会出现脏读、幻读等情况。
数据库定义了四种事务的隔离级别:

  • 串行化(Serializable)
  • 可重复读(Repeatable read)
  • 读已提交(Read committed)
  • 读未提交(Read uncommitted)

级别越高,效率越低。
MySQL的默认隔离级别是可重复读。
查询当前使用的隔离级别:select @@tx_isolation;
设置MySQL事务的隔离级别:set session transaction isolation level xxx;

事务的传播行为

A和B两个service层的方法都添加了事务控制,如果A调用B,就需要进行事务的一些协商,这叫做事务的传播行为。
此时,我们站在B的角度来观察定义事务的传播行为。
image.png

Spring中事务的API

MyBatis:sqlSession.commit();
Hibernate:session.commit();
Spring事务管理最核心的三个API:

  • TransactionDefinition

image.png

  • PlatformTransactionManager

image.png

  • TransactionStatus

image.png

Spring声明式事务配置

需要以下jar包支持:

  • spring-context
  • aspectjweaver
  • spring-jdbc
  • spring-tx

纯xml模式

一个demo:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--定制事务细节,传播行为、隔离级别等-->
    <tx:attributes>
        <!--一般性配置-->
        <tx:method name="*" read-only="false" propagation="REQUIRED" isolation="DEFAULT" timeout="-1"/>
        <!--针对查询的覆盖性配置-->
        <tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <!--advice-ref指向增强=横切逻辑+方位-->
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/>
</aop:config>

xml+注解模式

 <!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManage r">
    <property name="dataSource" ref="dataSource"></property> 
</bean>

<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"/>

然后在接口、类或者方法上添加@Transactional注解即可。

@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)

纯注解模式

把:

<tx:annotation-driven transaction-manager="transactionManager"/>

替换为注解@EnableTransactionManagement即可。