Spring-aop切面环绕通知

时间:2024-05-04 16:55:51

1.pom引入

<!-- 切面依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.定义注解:AroundAnnotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AroundAnnotation {
    String value() default "";
}

3.定义切面:Aspect

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

@Aspect
@Component
public class AroundAop {
    //  execution(* study.mapper.*(..)) @annotation(study.aop.AroundAnnotation)
    @Pointcut("execution(* study.mapper.*.*(..)) ")
    public void aspect(){

    }

    //定义@Around增强,poincut连接点使用@annotation(xxxx)进行定义 @annotation(study.aop.AroundAnnotation)
    @Around("@annotation(annotation)")
    public Object processTx(ProceedingJoinPoint joinPoint, AroundAnnotation annotation) throws Throwable {
        long startTime = System.currentTimeMillis();
        try {
            //AroundAnnotation annotation =joinPoint.getTarget().getClass().getAnnotation(AroundAnnotation.class);
            String value = annotation.value();
            System.out.println("arount 进入-----" + value);
            // 执行目标方法
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            System.out.println("执行目标方法:"+ joinPoint.getSignature() + " executed in " + (endTime - startTime) + "ms");
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            System.out.println("arount 出去 -----" );
        }

        return null;
    }


    @Before("aspect()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();    //获取方法入参
        System.out.println("before -- 原方法的入参是:"+args);
        System.out.println("before -- 原方法执行前会先执行我!!参数:" + args[0]);
    }


    @AfterReturning("aspect()")
    public void after(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();    //获取方法入参
        System.out.println("AfterReturning -- 原方法执行后会执行我!!参数:" + args);
    }


}

4.使用切面注解


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import study.aop.AroundAnnotation;
import study.entity.UserInfo;

@Mapper
public interface UserMapper extends BaseMapper<UserInfo> {

    @AroundAnnotation("AAAA")
    @Select("select * from t_user where id = #{id}")
    public UserInfo selectByIdFromMaster(@Param("id") Integer id);
    
}

5.执行结果