<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"); } }