使用注解启动AOP的增强实现分页
使用注解启动AOP的增强实现分页
第一步
引入需要的aop与分页的jar包
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.5</version>
</dependency>
第二步
创建注解类
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PageX {
}
第三步
创建切面类MyAop
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;
}
}
这样就可以实现只要在spring ioc容器的方法上添加我们写的注释就可以执行aop进行切面