spring基于注解得aop

bean.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: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="net.togogo"></context:component-scan>

    <!--配置spring开启注解aop的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
package net.togogo.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 记录日志的工具类,它里面提供了公共代码
 */
@Component("logger")
@Aspect//表示当前类是切面类
public class Logger {

    @Pointcut("execution(* net.togogo.service.impl.*.*(..))")
    private void pt01(){}
    /**
     * 前置通知
     */
    @Before("pt01()")
    public void beforePrintLog(){
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
    }


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

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

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

    
}

环绕通知:

@Around(("pt01()"))
    public Object aroundPrintLog(ProceedingJoinPoint proceedingJoinPoint){
        Object rtValue = null;
        try {
            Object[] args = proceedingJoinPoint.getArgs();//得到方法执行所需参数
            System.out.println("aroundPrintLog方法开始记录日志了。。。前置");
            rtValue = proceedingJoinPoint.proceed(args);//明确调用业务层方法(切入点方法)
            System.out.println("aroundPrintLog方法开始记录日志了。。。后置");

        } catch (Throwable throwable) {
            System.out.println("aroundPrintLog方法开始记录日志了。。。异常");
            throwable.printStackTrace();
        }finally {

            System.out.println("aroundPrintLog方法开始记录日志了。。。最终");
            return rtValue;
        }

    }

在这里插入图片描述

发布了31 篇原创文章 · 获赞 1 · 访问量 251

猜你喜欢

转载自blog.csdn.net/weixin_41605945/article/details/104498588