aop的使用
-
在切面类上使用@Aspect注解 @component
-
在类中定义切入点
@Pointcut("execution(* com.yunguanzu.aop.*.*(..))") public void 方法(""){}
-
切入点可以再切入点上配合这些方法使用
@Pointcut("@annotation(com.iboxpay.partner.common.annotation.HqkAppReponseHandle) || @within(com.iboxpay.partner.common.annotation.HqkAppReponseHandle)") public void hqkAppRequestHandle() { }
-
使用通知增强
@Aspect @Component public class TransactionAop { @Pointcut("execution(* com.jiuxian..service.*.*(..))") public void pointcut() { } @Before("pointcut()") public void beginTransaction() { System.out.println("before beginTransaction"); } @After("pointcut()") public void commit() { System.out.println("after commit"); } @AfterReturning("pointcut()", returning = "returnObject") public void afterReturning(JoinPoint joinPoint, Object returnObject) { System.out.println("afterReturning"); } @AfterThrowing("pointcut()") public void afterThrowing() { System.out.println("afterThrowing afterThrowing rollback"); } @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { try { System.out.println("around"); return joinPoint.proceed(); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { System.out.println("around"); } } }
解析注解
-
自定义注解
@Retention(RetentionPolicy.RUNTIME)//运行时有效 @Target(ElementType.METHOD)//作用于方法 public @interface MyAnnotation { String methodName () default ""; }
-
在controller中使用注解
@Controller @RequestMapping("/hello") public class HelloController { @RequestMapping("/login/{name}") @MyAnnotation(methodName = "login") public void login(@PathVariable String name){ System.out.println("hello!"+name); } }
-
在再增强或者切入点@pointcut中使用 @annotation()
@Around(value = "@annotation(around)") //around 与 下面参数名around对应 public void processAuthority(ProceedingJoinPoint point,MyAnnotation around) throws Throwable{ System.out.println("ANNOTATION welcome"); System.out.println("ANNOTATION 调用方法:"+ around.methodName()); System.out.println("ANNOTATION 调用类:" + point.getSignature().getDeclaringTypeName()); System.out.println("ANNOTATION 调用类名" + point.getSignature().getDeclaringType().getSimpleName()); point.proceed(); //调用目标方法 System.out.println("ANNOTATION login success"); }
@Pointcut(value = "@annotation(log)", argNames = "log") public void pointcut(MyAnnotation log) { } @Around(value = "pointcut(log)", argNames = "joinPoint,log") public Object around(ProceedingJoinPoint joinPoint, MyAnnotation log) throws Throwable { try { System.out.println(log.value()); System.out.println("around"); return joinPoint.proceed(); } catch (Throwable throwable) { throw throwable; } finally { System.out.println("around"); } } }
切面优先级
@order注解可以使用在类或方法上,但是,直接作用于方法上是无法奏效的,目前的使用方法都是通过标记在切面类上,来实现两个切面的优先级。