aop 拦截含有特定注解的类

您所在的位置:网站首页 aop拦截接口上的注解 aop 拦截含有特定注解的类

aop 拦截含有特定注解的类

2023-11-13 22:29| 来源: 网络整理| 查看: 265

1.功能点:使用aop拦截含有自定义注解的类

1.自定义注解

  

package com.zhuanche.common.dingdingsync; import java.lang.annotation.*; /** * @Author fanht * @Description 含有该注解的controller方法存储到mq * @Date 2019/2/28 上午11:26 * @Version 1.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.TYPE}) @Documented public @interface DingdingAnno { }

2.使用切面

package com.zhuanche.common.dingdingsync;

import org.aspectj.lang.JoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.*;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;

import java.lang.reflect.Method;import java.util.Arrays;

/** * @Author fanht * @Description * @Date 2019/2/28 上午11:59 * @Version 1.0 */@Component@Aspectpublic class DingdingAspect {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Pointcut("execution(* com.zhuanche.controller.driverteam.DriverTeamController.*(..))") public void pointCut(){ logger.info("含有自定义注解dingdingAnno的方法..."); }

@Before("pointCut() && @annotation(dingdingAnno) ") public void dingdingVerify(JoinPoint joinPoint,DingdingAnno dingdingAnno){ System.out.println("&&&&&&&&&&&&&&&&&&&&"); logger.info(joinPoint.getSignature().getName() + ",入参:{" + Arrays.asList(joinPoint.getArgs() + "}")); }

@AfterReturning("pointCut() && @annotation(dingdingAnno)") public void finish(JoinPoint jointPoint,DingdingAnno dingdingAnno){ logger.info(jointPoint.getSignature().getName() + "*********"); Signature signature = jointPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null){ dingdingAnno = method.getAnnotation(DingdingAnno.class); if (dingdingAnno != null){ System.out.println(jointPoint.getTarget().getClass().getName()); System.out.println(jointPoint.getSignature().getName()); System.out.println(jointPoint.getArgs().length); } }

System.out.println(jointPoint.getSignature().getName()); }}

3.配置aop

4.在类上面添加特定注解

@ResponseBody@RequestMapping(value = "/driverTeamDetail")@DingdingAnnopublic AjaxResponse driverTeamDetail(DriverTeamRequest param){ logger.info("查询车队详情入参:"+ JSON.toJSONString(param)); CarDriverTeamDTO detail = carDriverTeamService.selectOneDriverTeam(param); return AjaxResponse.success(detail);}

启动项目,遇到的几个问题:1.使用Jrebel 每次修改后,总是不成功,报各种异常。原因应该是 aop在spring启动时候就加载进去了,修改后需要重启;2.遇到的几个问题:1)启动报错

[Xlint:invalidAbsoluteTypeName]error     原因一般是point后面的地址错误,我的原因是后面多加了&& +自定义注解名称 2)没进入后置通知: 第一次的时候,写的是     @AfterReturning("within(com.zhuanche.controller..*) && @annotation(sdol)")没有成功,具体原因还不太清楚。  


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3