How to implement aop to set the default time reverse order of all paging

You can use Spring AOP (aspect-oriented programming) to achieve a unified reverse time sorting requirement. The following is a sample code that demonstrates how to use Spring AOP to intercept all annotated @GetMappingmethods, Querymodify the object, and add the default reverse chronological ordering rule:

First, configure the AOP proxy in your Spring Boot application:

@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}

Then, create an aspect class to implement the interception and processing of the request method:

@Aspect
@Component
public class DefaultSortAspect {
    
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void getMappingMethods() {
    }

    @Around("getMappingMethods()")
    public Object applyDefaultSort(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法的参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof Query) {
                Query query = (Query) arg;
                // 如果查询对象中没有指定排序规则,则添加默认的时间倒序排序规则
                if (query.getAsc() == null && query.getDesc() == null) {
                    query.setDesc("update_time");
                }
            }
        }
        // 继续执行原有的请求方法
        return joinPoint.proceed();
    }
}

In the above code, we define a pointcut  getMappingMethods()which will match all @GetMappingannotated methods. We use  @Around annotations to implement surround notifications for these methods, and ProceedingJoinPoint the parameters represent the intercepted methods.

In the aspect method  applyDefaultSort() , we first obtain the parameters of the method, and then traverse all the parameters to determine whether there is  Query an object. If present, and no collation is specified in the query object, a default reverse-chronological collation is added.

Finally, we  joinPoint.proceed() continue to execute the original request method by calling it to ensure that the request can return normally.

@GetMapping Through the above code configuration and aspects, you can implement the default reverse chronological ordering requirements on all annotated  methods, without having to deal with them separately in each method.

Guess you like

Origin blog.csdn.net/weixin_42759398/article/details/131852448