SpringBoot利用@Aspect实现AOP

pom依赖


    commons-collections
    commons-collections
    3.2


    org.aspectj
    aspectjrt
    1.9.2


    org.springframework.boot
    spring-boot-starter-aop
    2.1.4


自定义一个注解

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 LogRecord {
    String logRecord() default "";
}

编写Aspect切面

import com.yunzhitx.mall.admin.controller.core.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Aspect
public class LogRecordAdvice {
    /**
    *一 、利用注解的方式
    */
    @Before("@annotation(logRecord)")
    public void before(JoinPoint point, LogRecord logRecord){
        System.out.println("前置增强");
    }

    @AfterReturning(returning = "obj",pointcut="@annotation(logRecord)")
    public void after(JoinPoint point,Object obj,LogRecord logRecord){
        // obj 为接口的返回值(用于记录操作对象), logRecord 为接口上打得注解
        System.out.println("后置增强");
        String record = logRecord.logRecord();
        log.info(record);
    }

    @AfterThrowing("@annotation(logRecord)")
    public void afterThrowing(JoinPoint point,LogRecord logRecord){

    }


    /**
    *二、Pointcut的方式,完成对com.yunzhitx.community.controller.template.topic包下所有类增强
    */
    @Pointcut("within(com.yunzhitx.community.controller.template.topic..*)")
    public void adminValidatePointcut(){
    }

    @Before("adminValidatePointcut()")
    public void adminValidateBefore(){
       System.out.println("Pointcut的方式,前置增强");
    }

    /**
     * Pointcut + annotation方式 配置织入点
     */
    @Pointcut("@annotation(com.yunzhitx.community.controller.log.LogRecord)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            // 获取方法上的注解
            LogRecord log= method.getAnnotation(LogRecord.class);
            // 业务...
        }
    }


}

注解方式,需要增强的方法上打上自定义注解

@RestController
@RequestMapping("api/v1/item/itemCategory")
public class ItemCategoryRest  {

    @PostMapping("add")
    @LogRecord(logRecord = "新增商品分类")
    public InvokeResult add(@RequestBody @Valid ItemCategoryCreateCommand command) {
        ItemCategory itemCategory = ItemCategoryAssembler.toItemCategory(command);
      //  itemCategoryService.addItemCategory(itemCategory);
        return InvokeResult.success(itemCategory.getId());
    }
}

你可能感兴趣的:(java)