springboot中springAOP的使用
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
package cn.fff.test.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TrackTime { String param() default ""; }
package cn.fff.test.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class TrackTimeAspect { @Pointcut("execution(* cn.fff.test.GirlService.aopDemo(..))") public void aopDemo() {} @Before("TrackTimeAspect.aopDemo()") public void before(JoinPoint joinPoint) { System.out.println(" -------------> Before Aspect "); System.out.println(" -------------> before execution of " + joinPoint); } /*@Around("@annotation(trackTime)") public Object around(ProceedingJoinPoint joinPoint, TrackTime trackTime) throws Throwable { Object result = null; long startTime = System.currentTimeMillis(); result = joinPoint.proceed(); long timeTaken = System.currentTimeMillis() - startTime; System.out.println(" -------------> Time Taken by " + joinPoint + " with param[" + trackTime.param() + "] is " + timeTaken); return result; }*/ @Around("@annotation(trackTime)") public void around(ProceedingJoinPoint joinPoint, TrackTime trackTime) throws Throwable { System.out.println("玩地地道道的"); joinPoint.proceed(); System.out.println(" -------------> Time Taken by " + joinPoint + " with param[" + trackTime.param() + "] is "); } }
package cn.fff.test; import cn.fff.test.aop.TrackTime; import org.springframework.stereotype.Service; @Service public class GirlService { @TrackTime(param = "myService") public void getAge(Integer id){ Integer age =id; System.out.println("环绕通知"); if (age <= 10) { throw new GirlException(ResultEnum.PRIMARY_SCHOOL); } if (age < 16) { throw new GirlException(ResultEnum.MIDDLE_SCHOLL); } } public void aopDemo() { System.out.println("defdfdfdfddfdf"); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步