Thursday, 27 June 2013

Intercept an @annotation with Aspetcj in Spring

Intercepting a method call marked with an @Annotation using AspectJ and Spring it's easy enough and it's a good approach in terms of flexibility, scalability and design.

  • It's flexible because in the case you want to intercept a different method, you just have to move your annotation somewhere else.
  • It's scalable because if you want to intercept more than one method, you just need to add the annotation in other methods.
  • It results also in a good and clean code.

First thing you need to do is include the dependencies. In case of maven the following will do it.
<!-- Dependencies for AspectJ and Spring AOP -->

Second, we need to create the annotation that we will use to mark the methods in the business logic.
package com.marco.aspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public @interface CommitTransaction {

Now, we need to create an interceptor. In this case (@After) it will be triggered when the method intercepted is finished.
For the full list of pointcuts and advises see the following pointcuts and advise
package com.marco.aspect;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import com.marco.some.package.SomeClass;
import com.marco.some.package.SomeBean;
public class CommitTransactionInterceptor {

        private static final Logger LOGGER = Logger.getLogger(CommitTransactionInterceptor.class);

        private SomeBean someBean;

        public void after() {

                LOGGER.debug("An invocation to " + SomeClass.class.getSimpleName() + " has been intercepted.");



Activate the aspectj and the interceptor in Spring adding the following in your application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" xmlns:xsi="" xmlns:aop=""

        <aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true" />

        <bean id="commitTransactionInterceptor" class="com.marco.aspect.CommitTransactionInterceptor"/>

And of course, remember to load it in your spring configuration classes
@ImportResource({ "classpath:application-context.xml" })
public class YourSpringConfiguration {

All done, now you can mark all the methods you want to intercept with your annotation and you will see the magic happening.

public class SomeLogic {

        private static final Logger LOGGER = Logger.getLogger(SomeLogic.class);

        public void executeSomeLogic(Object someObject) {
             // a transaction finished