Posts Tagged ‘AspectJ’

AOP really easy with Spring/AspectJ

29. August 2009

Aspect-oriented programming (AOP) is a programming paradigm that increases modularity by enabling improved separation of concerns. While object oriented programming paradigms support encapsulation of concerns, some concerns defy these forms of implementation and are called crosscutting concerns because they “cut across” multiple abstractions in a program. Logging is a common example of a crosscutting concern because a logging strategy necessarily affects every single logged part of the system.

For introducing AspectJ based AOP within the well-known Spring Framework, we just need a few lines of Spring Configuration

<!-- Activating AspectJ in Spring Config -->
<aop:aspectj-autoproxy/>

<!-- Configuring the Bean declaring the Aspect -->
<bean id="testAspect" class="spring.demo.TestAspect"/>

<!-- Some Test Bean to demonstrate the Aspect Execution -->
<bean id="test" class="spring.demo.Test"/>

plus: the Class declaring the Aspect, of course

@Aspect
public class TestAspect {

    @Pointcut("execution(* *(..))")
    public void methodExecution() {}

    @Around("spring.demo.AspectJTest.TestAspect.methodExecution()")
    public Object doTrace(ProceedingJoinPoint pjp) throws Throwable {
        Log log = LogFactory.getLog(pjp.getSignature().getDeclaringType());
        Object retVal;
        log.info("Starting method " + pjp.getSignature().toLongString());
        retVal = pjp.proceed();
        log.info("Ending method " + pjp.getSignature().toLongString());
        log.info("Method returned " + retVal);
        return retVal;
    }

}

As this Aspect triggers the @Around method on every method execution invoking the method boolean doSomething(boolean) on our Test Class

public class Test {
    public boolean doSomething(boolean param) {
        LogFactory.getLog(getClass()).info("About to return " + param);
        return param;
    }
}

will lead to something like the following sample output proving the execution of the TestAspect.doTrace(...) method:

Starting method public boolean spring.demo.Test.doSomething(boolean)
About to return true
Ending method public boolean spring.demo.Test.doSomething(boolean)
Method returned true

which is nice, actually. The Full Spring Guide on this can be found here