publicclassUserManager{/*這個方法需要一個參數(shù)*/publicvoidaddUser(Stringuser){System.out.println("addUser(String str) method is executed!");}publicvoiddeleteUser(){System.out.println("deleteUser() method is executed!");}/*這個方法返回一個字符串*/publicStringgetUser(){System.out.println("getUser() method is executed!");return"Hello";}/*這個方法拋出一個異常*/publicvoideditUser()throwsException{thrownewException("something is wrong.");}}
@AspectpublicclassExampleAspect{@Pointcut("execution(* com.psjay.example.spring.aop.*.*(..))")publicvoidaPointcut(){}@Before("aPointcut()")publicvoidbeforeAdvice(){System.out.println("before advice is executed!");}@AfterReturning(pointcut="aPointcut()",returning="r")publicvoidafterReturningAdvice(Stringr){if(r!=null)System.out.println("after returning advice is executed! returning String is : "+r);}@After("aPointcut()")publicvoidAfterAdvice(){System.out.println("after advice is executed!");}@After("aPointcut() && args(str)")publicvoidAfterAdviceWithArg(Stringstr){System.out.println("after advice with arg is executed!arg is : "+str);}@AfterThrowing(pointcut="aPointcut()",throwing="e")publicvoidafterThrowingAdvice(Exceptione){System.out.println("after throwing advice is executed!exception msg is : "+e.getMessage());}}
publicclassTest{publicstaticvoidmain(String[]args){ApplicationContextctx=newClassPathXmlApplicationContext("applicationContext.xml");UserManagerum=ctx.getBean("userManager",UserManager.class);System.out.println("------ Case 1 --------");um.addUser("hey");System.out.println("------ Case 2 --------");try{um.editUser();}catch(Exceptione){}System.out.println("------ Case 3 --------");um.getUser();}}
測試結(jié)果:
------ Case 1 --------
before advice is executed!
addUser(String str) method is executed!
after advice is executed!
after advice with arg is executed!arg is : hey
------ Case 2 --------
before advice is executed!
after advice is executed!
after throwing advice is executed!exception msg is : something is wrong.
------ Case 3 --------
before advice is executed!
getUser() method is executed!
after returning advice is executed! returning String is : Hello
after advice is executed!