AOP+ user defined annotation to automatically set paging parameters

In actual development, we often encounter some paging query requirements, and the front end generally only gives the back-end two parameters: page number and page size. The back-end needs to calculate start and end. Using AOP+ user-defined annotations, the code that calculates start and end is extracted and put into the aspect to reduce repeated code.

The codes are as follows:

Define a base class of PageParam, which can be implemented by all parameter classes that need paging properties.
It has two main functions:

  1. Abstract the common start, end, page and pageSize
  2. Judge in the aspect, and calculate only when the parameter class is a subclass of this class
public class PageParam {
    public String start;
    public String end;
    public int page;
    public int pageSize;

    public String toString() {
        return "PageParam{" +
                "start='" + start + '\'' +
                ", end='" + end + '\'' +
                ", page=" + page +
                ", pageSize=" + pageSize +

Customize an annotation and add it to the method that needs to set the paging attribute
You can add some restrictions to this annotation (meta annotation), which is not added here for convenience

 * Support paging parameters
public @interface PageAware {

Define a facet in which to calculate paging properties
Pointcut is a method with @PageAware added
Use a surround notification to get the parameter before calling the connection point method. If the parameter is a subclass of PageParam, set the paging property

public class MyAspect {

    public void myPointCut(){}

    public Object myAdivce(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();

        if(args[0] instanceof PageParam){
            PageParam pageParam = (PageParam) args[0];
            int page = < 1 ? 1:;
            int pageSize = pageParam.pageSize < 0 ? 5 : pageParam.pageSize;
            pageParam.start = String.valueOf((page-1)*pageSize + 1);
            pageParam.end = String.valueOf(page*pageSize);
        return joinPoint.proceed();

Test class

public class TestCtr {

    // Paging query Users
    // Add PageAware to obtain the settings for automatically setting the paging parameters of the first parameter user
    // The User must be a subclass of PageParam, and the paging parameters are calculated for the User in the aspect
    public void getUsers(@RequestBody User user){


Parameter class tested

// Inherit PageParam and have some parameters of paging
public class User extends PageParam {
    public String name;

    public String toString() {
        return "name = " + name+super.toString();

Test results: use postMan to call the interface of paging query user, and aop will intercept the query method and set the paging attribute

Tags: Java

Posted by domwells27 on Mon, 30 May 2022 21:37:46 +0530