使用注解作为AOP的切入点(@Pointcut)

错误日志

在使用aop的注解切入时…

  • 引入jar包

    • <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
      </dependency>
      
  • 创建切面类

    • import com.github.pagehelper.Page;
      import com.github.pagehelper.PageHelper;
      import org.aspectj.lang.ProceedingJoinPoint;
      import org.aspectj.lang.annotation.*;
      import org.springframework.stereotype.Component;
      import org.springframework.web.context.request.RequestContextHolder;
      import org.springframework.web.context.request.ServletRequestAttributes;
      
      import javax.servlet.http.HttpServletRequest;
      
      //标注是一个aop
      @Aspect
      @Component
      public class MyAop {
          //切入点设置设置注解
          @Pointcut("@annotation(com.xhlin.annotation.PageX)")
          public void point(){}
      
          // 环绕通知
          @Around("point()")
          public Object around(ProceedingJoinPoint pjp) throws Throwable {
      
              System.out.println("环绕前");
              ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
              HttpServletRequest request = attributes.getRequest();
              String pageNum = request.getParameter("pageNum");
              String pageSize = request.getParameter("pageSize");
              if (pageSize !=null && pageNum!= null){
                  int page_num = Integer.valueOf(pageNum);
                  int page_size = Integer.valueOf(pageSize);
                  PageHelper.startPage(page_num,page_size);
              }
      
              Object proceed = pjp.proceed();
              if (proceed instanceof Page){
                  proceed = (Page) proceed;
              }
      
              System.out.println("环绕后");
              return proceed;
          }
      
      }
      
  • 创建注解类

    • import java.lang.annotation.*;
      
      @Target({ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      public @interface PageX {
      }
      
  • 在要被调用的方法上面添加注解

    • import java.util.List;
      
      public interface UserExcelService {
          @PageX
          List<UserExcel> selects();
      }
      

开启程序…

运行结果…

咦?为什么aop没有生效?

检查代码发现,如果你使用的是 controller->service->mapper 在接口中定义的方法添加注解,我们的aop在容器中找注解时会找不到,因为service接口没有注入到spring ioc中

修改代码:把注解移到mapper接口中的方法。(因为@mapper注释了mapper接口,这个@mapper注解会被用于spring和mybatis链接的@MapperScan扫描)


版权声明:本文为nidimyger原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。