AOP using AspectJ and annotation in Spring

Posted on 21-01-2015 13:52 by graham
Let's say we want to add logging to all methods annotated with @Logging using AOP.

We will start with creating the @Loggin annotation.
package com.wordgraphs.aspectj;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public @interface Logging


The we create an aspect that will wrap every call of every method annotated with @Logging:
package com.wordgraphs.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

public class LoggingAspect
private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

@Around("execution(* *(..)) && @annotation(AccessRestriction)")
public Object around(ProceedingJoinPoint point) throws Throwable
long start = System.currentTimeMillis();
Object result = point.proceed();"Method lasted " + System.currentTimeMillis() - start);
return result;

In order for this to work, we will need some dependencies in our POM file:



In your app-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<!-- enable AOP -->
<aop:aspectj-autoproxy />


And finally annotate some method with the @Logging annotation to see if it's actually working:
public void myMethod()
// do something


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems