10

From my research I know there are two ways of using AspectJ. First is by creating A.aj class and second by adding annotation @Aspect in A.java.

I was looking for a good tutorial for this second kind, especially about lines like

@After("call(void fooMethod())")  
@Around("call(void sendAndReceive())") 
@Before("execution(String greeting(..)) && args(context)")

but I don't know how they are called.

Could you recommend some tutorials?

alicjasalamon
  • 4,171
  • 15
  • 41
  • 65

2 Answers2

11

This style is called @AspectJ to emphasize the role of annotations. Have a look at official docs and @AspectJ cheat sheet.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

Annotation and the XML ways:

Annotation way: Minimal xml Config file:

<!-- Enable autoproxy to pick up all Java files tagged as @Aspect behave like Aspects -->
<aspectj-autoproxy/>
<!-- define bean -->
<!-- Note: MyUselessAspect.java should exist and this class must be tagged as @Aspect -->
<bean id="myUselessAspect" class="...MyUselessAspect" />

XML way: Minimal XML configuration:

<aop:config>
   <aop:aspect ref="myUselessAspect">
        <!-- this point-cut picks all methods of any return type, from any package/class with any number of Parameters -->
    <aop:before method="doSomethingBeforeMethodCall" pointcut="execution(* *.*(..))"/>
    <aop:after method="doSomethingAfterMethodCall" pointcut="execution(* *.*(..))"/>
   </aop:aspect>        
</aop:config>
<!-- No need to Annotate this java Class as @Aspect. Neither you need to define any
 Point-cuts or Advices in the Java file. The <aop:config> tag takes care of everything -->
<bean id="myUselessAspect" class="...MyUselessAspect"></bean>

No changes in code required.

Pre-Req: aop Namespace must exist in the XML file

Vikram
  • 4,162
  • 8
  • 43
  • 65
  • Noting for the benefit of people using AspectJ, but not familiar with Spring -- Vikram's answer here is addressing how to configure aspects in Spring's configuration file. Also, he's offering a *third* way to define an aspect -- via the XML configuration file. A similar capability is available in the AspectJ configuration file (typically called 'aop.xml'), when you're programming directly in AspectJ, rather than Spring. Unfortunately, this isn't addressing the original question. – Bob Kerns Jun 20 '13 at 15:58