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
<context:component-scan base-package="com.zhuanche.**"/><!--开启aop注解 --><aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> 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)启动报错
原因一般是point后面的地址错误,我的原因是后面多加了&& +自定义注解名称
2)没进入后置通知: 第一次的时候,写的是
@AfterReturning("within(com.zhuanche.controller..*) && @annotation(sdol)")没有成功,具体原因还不太清楚。
原文地址:https://www.cnblogs.com/thinkingandworkinghard/p/10453662.html
时间: 2024-10-31 08:48:04