Skip to content
tylertreat edited this page Jan 20, 2013 · 1 revision

An aspect separates cross-cutting concerns from core application code by providing pointcut advice. Aspects can be registered using either XML declarations in infinitum.cfg.xml or through annotations. The Aspect annotation indicates that a class contains advice functionality which can be applied to a join point.

In order to use annotations to declare aspects, component scanning must be enabled in infinitum.cfg.xml:

<component-scan base-package="com.foo.bar" />

Declaring Aspects

Take, for example, the class below which defines an aspect with three advice methods.

public class LoggingAspect {

    public void logBefore(JoinPoint joinPoint) {
        Log.d("LoggingAspect", "Before advice: " + joinPoint.getMethod().getName());
    }

    public void logAfter(JoinPoint joinPoint) {
        Log.d("LoggingAspect", "After advice: " + joinPoint.getMethod().getName());
    }

    public Object logAround(ProceedingJoinPoint joinPoint) {
        Log.d("LoggingAspect", "Around advice: " + joinPoint.getMethod().getName());
        Object result = joinPoint.proceed();
        Log.d("LoggingAspect", "Around advice: " + joinPoint.getMethod().getName());
        return result;
    }

}

An XML aspect declaration for the above class might look something like the following in infinitum.cfg.xml:

<aspect id="loggingAspect" class="com.foo.bar.aspect.LoggingAspect">
    <advice id="logBefore" type="before" pointcut="beans" value="myService" />
    <advice id="logAfter" type="after" pointcut="beans" value="myService" />
    <advice id="logAround" type="around" pointcut="within" value="com.foo.bar.dao" />
</aspect>

Using annotations, this XML declaration is unneeded. The advice metadata can be provided in the Java class using the Before, After, and Around annotations, and component scanning will automatically register the aspect. Thus, the class can be defined as follows:

@Aspect
public class LoggingAspect {

    @Before(beans = { "myService" })
    public void logBefore(JoinPoint joinPoint) {
        Log.d("LoggingAspect", "Before advice: " + joinPoint.getMethod().getName());
    }

    @After(beans = { "myService" })
    public void logAfter(JoinPoint joinPoint) {
        Log.d("LoggingAspect", "After advice: " + joinPoint.getMethod().getName());
    }

    @Around(within = { "com.foo.bar.dao" })
    public Object logAround(ProceedingJoinPoint joinPoint) {
        Log.d("LoggingAspect", "Around advice: " + joinPoint.getMethod().getName());
        Object result = joinPoint.proceed();
        Log.d("LoggingAspect", "Around advice: " + joinPoint.getMethod().getName());
        return result;
    }

}

Clone this wiki locally