AOP的环绕切点的应用:公共方法写基本的增删改查(此方法只需要在Controller层写,其他层不需要写代码了)

在实际项目中碰到的好的切面加强的应用方式

1.获取切面加强目标方法的所有信息

对于ProceedingJoinPoint的应用

Proceedingjoinpoint 继承了 JoinPoint。是在JoinPoint的基础上暴露出 proceed 这个方法。proceed很重要,这个是aop代理链执行的方法。

环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的
注:ProceedingJoinPoint is only supported for around advice 这个类仅仅只支持环绕通知

//指定扫描的包路径
@pointcut(value="execution(*.com.xxxx.app.server.controller.*.target*(..))")
public void targetController(){}

@around("targetController()")
public object around(ProcedingJoinPoint joinPoint) throw Throwable{
//获取请求目标的类名
Srting className=joinPoint.getTarget().getClass().getSimpleName();
//获取请求方法名
String methodName=joinPoint.getSignatrue.getName();
//获取目标方法的注解
Method method = null;
joinPoint.getTarget().getClass().getMethods
for (Method m : joinPoint.getTarget().getMethods()) {
     if(m.getName().equals(methodName)){
             method=m;
   xxxxxx annoObj  =method.getAnntation(xxxxx.class)   //xxxxx.class注解的类型
 }
}

//获取请求目标的参数
Object arg=joinPoint.getArgs()[0];

joinPoint.getTarget()能获取目标对象,就能获取类,方法,等等信息

///上述我们能获取环绕目标的所有信息,那么我们根据这个我们能写出一个公共方法出来,其他Controller层只是一个接口,所有简单的增删改查就在这个方法实现就好了

2.调用公共方法

2.1Contoller层方法

@PostMapping("/page") //Type只表示随意入参
Public ResultBase<XXXXX> targetPage(@ResquestBody  Type type){
    reture new ResultBase<xxxxxx>(null,new Parameter().set(xxxxx))
}

Contoller层可以做一些参数的设置

2.2 获取Contoller层的参数设置

//新对象
Parameter param =new Parameter();
//执行Controller层方法,Controller层方法只是一些参数的设置
Object object=joinPoint.proceed(joinPoint.getArgs())
//对返回结果进行一个处理,获取Controller层参数设置
if(null!=object){
ResultBase<?> resultBase  = (ResultBase<?>) object;
param=result.getParam;   //ResultBase<?>有这两个参数,不用理会
object=resultBase.getDate();  
}

2.3根据目标方法类型调用公用方法

//所有的Service层实现类都要实现这个接口,以便于转换
CommonService service;

//获取注解,(Controller上要有@SimpleService(xxxxx.class))是否需要扫描,
SimpleService annotation =joinPoint.getTarget.getClass.getAnnotation(SimpleService.class);

//告诉实现类是哪个
if(null!=annotation){/
  service=(CommonService) SpringContextUtils.getBean(annotation.value());
}
//根据请求方法名称调用哪个具体公共方法
if(methodName.contains(targrtPage)){
  object  =service.getpage(param)
}
//对返回结果在处理,做到统一返回
  object=ResultUtils.ok(object)
  return object;

这样就能做到只需要写一个Controller,其他都只需要在专门的公共方法类里写就好了

参考:(107条消息) SpringAOP中的JointPoint和ProceedingJoinPoint使用详解(附带详细示例)_如何在5年薪百万的博客-CSDN博客_proceedingjoinpoint有什么用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值