Another nice example using Advices. You can define an Advice without a PointCut method.
authorgumartinm <gu.martinm@gmail.com>
Sun, 1 Jan 2012 07:17:31 +0000 (08:17 +0100)
committergumartinm <gu.martinm@gmail.com>
Sun, 1 Jan 2012 07:17:31 +0000 (08:17 +0100)
The Advice itself may define the PointCut.

SpringJava/SpringAspectJ/spring-aspectj-example/src/main/java/de/spring/example/MyAdvice.java
SpringJava/SpringAspectJ/spring-aspectj-example/src/main/java/de/spring/example/SpringStart.java
SpringJava/SpringAspectJ/spring-aspectj-example/src/main/java/de/spring/example/web/Test.java

index d45504c..728b78b 100644 (file)
@@ -1,5 +1,7 @@
 package de.spring.example;
 
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
 
@@ -13,4 +15,26 @@ public class MyAdvice {
        public void doAccessCheck() {
                System.out.println("I am the Advice and I will be run before.");
        }
+       
+       
+       //NOTICE: YOU DO NOT NEED TO CREATE A SPECIAL CLASS FOR POINTCUTS
+       //        YOU COULD DEFINE AN ADVICE WITHOUT A POINTCUT
+       //This advice has a PointCut defined like execution(* de.spring.example.web.Test.anotherExample())
+       //right here wihout a special PointCut method. This advice has itself the PointCut
+       @Around("execution(* de.spring.example.web.Test.anotherExample())")
+       public Object doAround(ProceedingJoinPoint pjp) {
+               System.out.println("I am the Advice and I will be run before and after. BEFORE");
+               // start stopwatch
+               // This local variable will store the returned value from the method anotherExample()
+           Object retVal=null;
+               try {
+                       //Calling the real method
+                       retVal = pjp.proceed();
+               } catch (Throwable e) {
+                       e.printStackTrace();
+               }
+           // stop stopwatch
+           System.out.println("I am the Advice and I will be run before and after. AFTER " + retVal);
+           return retVal;
+       }
 }
index c378221..66285c2 100644 (file)
@@ -13,5 +13,6 @@ public class SpringStart {
                
                Test test = (Test) SpringContextLocator.getInstance().getBean("test");
                test.myMethod();
+               test.anotherExample();
        }
 }
index 3df70ac..1a8224c 100644 (file)
@@ -9,4 +9,11 @@ public class Test {
                //This value will be caught by the Advice with the @AfterReturning annotation.
                return 666;
        }
+       
+       public int anotherExample()
+       {
+               System.out.println("The Advice should be run before and after.");
+               return 666;
+               
+       }
 }