Tuesday, April 26, 2016

Spring AOP AspectJ Advice

An advice is really simple,
If config it in xml:
package com.gvace.aop;

/*
 * To define an Aspect
 * 
 */
public class SecurityHandler {

 private void checkSecurity() {
  System.out.println("Runned checkSecurity");
 }
}


If with Annotation
package com.gvace.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;


/*
 * To define an Aspect
 * 
 */
@Aspect
public class SecurityHandler {
 //@Pointcut Describe the target functions
 //So this function is ONLY JUST A FLAG, it will NEVER be called anyway
 //(* add*(..)), means return any type, name likes "add*", parameter can be anything 
 // the addAddMethod function does not want parameter and return type
 @Pointcut("execution(* add*(..))")
 private void addAddMethod(){}
 
 
 //define this Advice is run before target function
 //And it applied to some @Pointcut described functions
 @Before(value = "addAddMethod()")
 //@After(value = "addAddMethod()")
 private void checkSecurity() {
  System.out.println("Runned checkSecurity");
 }
}



Add a JoinPoint argument to get target class method information
package com.gvace.aop;

import org.aspectj.lang.JoinPoint;

/*
 * To define an Aspect
 * 
 */
public class SecurityHandler {
 //add a JoinPoint argument to get target class method information

 private void checkSecurity(JoinPoint joinPoint){
  System.out.println("Method name: "+joinPoint.getSignature().getName());
  for(int i=0; i<joinPoint.getArgs().length; i++){
   System.out.println(joinPoint.getArgs()[i]);
  }
  System.out.println("Runned checkSecurity");
 }
}

No comments:

Post a Comment