Spring中的AOP(4)

Spring中的基于注解的AOP

基于注解的AOP配置

通知类型标签
前置通知@Before
后置通知@AfterReturning
异常通知@AfterThrowing
最终通知@After
环绕通知@Around

其他注解:

配置Spring创建容器是要扫描的包
@ComponentScan(basePackages=“com.itheima”)代替 <context:component-scan base-package="com.toulan"></context:component-scan>

配置Spring开启注解的AOP支持
@EnableAspectJAutoProxy代替<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

@Aspect
表示当前类是一个切面类

@Pointcut(“execution(* com.toulan.service.impl..(…))”)
切入点表达式
基于注解的示例代码

@Component("logger")
//表示当前类是一个切面类
@Aspect
public class Logger {
	//切入点表达式
    @Pointcut("execution(* com.toulan.service.impl.*.*(..))")
    public void pt(){}

    /**
     * 前置通
     */
    @Before("pt()")
    public  void beforePrintLog(){
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
    }

    /**
     * 后置通知
     */
    @AfterReturning("pt()")
    public  void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
    }
    /**
     * 异常通知
     */
    @AfterThrowing("pt()")
    public  void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
    }

    /**
     * 最终通知
     */
    @After("pt()")
    public  void afterPrintLog(){
        System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
    }

    /**
     * 环绕通知
     * 问题:
     *      当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
     * 分析:
     *      通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
     * 解决:
     *      Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
     *      该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
     *
     * spring中的环绕通知:
     *      它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
     */
    //@Around("pt()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数
            //System.out.println(args[0]);
            System.out.println();
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }
}
<?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
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置Spring创建容器是要扫描的包-->
    <context:component-scan base-package="com.toulan"></context:component-scan>

    <!--配置Spring开启注解的AOP支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Override
    public void saveAccount() {

        //int i = 1 / 0;
        System.out.println("账户保存成功");

    }

    @Override
    public void updateAccount(int i) {
        System.out.println("账户更新成功"+i);
    }

    @Override
    public int deleteAccount() {
        System.out.println("账户删除成功");
        return 0;
    }
}

运行结果:
在这里插入图片描述
我们发现,运行结果与之前的稍有不同,之前的最终通知最后打印,现在不是啦,我们知道,后置通知和异常通知互斥, 如果出现异常通知,后置通知就会消失。所以我们自定异常
在这里插入图片描述
我们发现,后置通知不存在了,所以我们知道了,Spring基于AOP的注解中确实有顺序调用的问题,但是如果我们自己设置环绕通知,就不会有这中情况,因为,那是我们想怎么调用就怎么调用,如下
伪代码如下:

@Around("pt()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数
            //System.out.println(args[0]);
            System.out.println();
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }

在这里插入图片描述

上面的源码:请点击

基于xml的SpringAOP的转账操作的案例代码

基于注解的SpringAOP的转账操作的案例代码

在基于注解的SpringAOP配置中我们发现,在程序运行的时候我们发现报错:
在这里插入图片描述
Can’t call commit when autocommit=true,在上面我们提到在基于注解的AOP中,存在执行顺序的问题,我们知道在注解的AOP中,执行顺序是
在这里插入图片描述
原因分析:
注解AOP控制事务的问题分析
环绕通知主要代码如下:

@Component("txManager")
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;
    
    @Pointcut("execution(* com.yage.service.impl.*.*(..))")
    public void pt1(){}

    /**
     * 开启事务
     */
    //@Before("pt1()")
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    //@AfterReturning("pt1()")
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    //@AfterThrowing("pt1()")
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭事务
     */
   // @After("pt1()")
    public void release(){
        // 我们这里将连接关闭,其实并没有关闭,而是将连接还回到连接池中。
        // 当然线程也是一样,我们将线程关闭其实并不是将线程关闭,而是将线程还回到线程池中,
        // 这就出现了问题,我们并没有将线程彻底关闭,那么下一次再 connectionUtils.getThreadConnection()
        // 的方法中,因为我们的连接和线程是绑在一起的,所以我们可能获得的是一个已经还回到线程池中的线程的连接,
        // 该连接当然是无效的,所以我们要在最后将线程和来连接进行解绑。
        try {
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 环绕通知
     * @param pjp
     * @return
     */
    @Around("pt1()")
    public Object aroundAdvice(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try {
            //1.获取参数
            Object[] args = pjp.getArgs();
            //2.开启事务
            this.beginTransaction();
            //3.执行方法
            rtValue = pjp.proceed(args);
            //4.提交事务
            this.commit();

            //返回结果
            return  rtValue;

        }catch (Throwable e){
            //5.回滚事务
            this.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.释放资源
            this.release();
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值