在实际项目中碰到的好的切面加强的应用方式
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,其他都只需要在专门的公共方法类里写就好了