[color=red][size=large]可以直接运行test
项目见附件[/size][/color]
项目见附件[/size][/color]
package com.xxp.aoptest.aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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;
@Component
@Aspect
public class MyAspect {
@Pointcut(value="execution(* com.xxp.aoptest.programs.*.*(..)) && args(value)")//匹配com.xxp.aoptest.programs包中的所有类中的所有方法,并获得形参value
// @Pointcut(value="execution(* com.xxp.aoptest.programs.MyProgram.show(..))")//匹配com.xxp.aoptest.programs.MyProgram类中的所有show()方法(任意个参数) --pointcut2
// @Pointcut(value="execution(* com.xxp.aoptest.programs.MyProgram.show(String))")//匹配com.xxp.aoptest.programs.MyProgram类中的所有show(String value)方法 --pointcut3
public void showPoint(String value){}//声明切入点,方法名showPoint(value)为该切入点名称
/* 注意
* 如果不需要传递参数,则通知方法也要对应。(比如用以上pointcut3时,切入点也应修改为public void showPoint(){})
* */
@Before(value="showPoint(value)")//value值为切入点名称
public void doBefore(JoinPoint joinPoint,String value) throws Throwable{
System.out.println("before value="+value);
joinPoint.getArgs();//也可以用这个方法获得所有参数,这是就不需要在pointcut中使用args匹配了
}
@After(value="showPoint(value)")
public void doAfter(JoinPoint joinPoint,String value){
System.out.println("after value="+value);
}
@AfterReturning(value="showPoint(value)",returning="returnValue")
public void doAfterReturning(int returnValue,String value){
System.out.println("after returning:"+returnValue);
}
@AfterThrowing(value="showPoint(value)",throwing="error")
public void doAfterThrowing(JoinPoint joinPoint,Throwable error,String value){
System.out.println("error:"+error);
}
@Around("showPoint(value)")
public void doAround(ProceedingJoinPoint proceedingJoinPoint,String value) throws Throwable{
System.out.println("around start");
proceedingJoinPoint.proceed();
// proceedingJoinPoint.proceed(new Object[]{"reValue"});//将value的值改为reValue
System.out.println("around end");
}
}
package com.xxp.aoptest.programs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyProgram {
@RequestMapping(value="/show",method=RequestMethod.GET)
@ResponseBody
public int show(String value){
System.out.println("MyProgram show("+value+")");
String test = "test";
if (value.equals("SB")) {
throw new RuntimeException();
}
value = "GNB";
return 1;
}
public int show(){
System.out.println("MyProgram show()");
String test = "test";
return 1;
}
}