Enterprise Java

Spring – Adding AOP support

I heard a story about one senior (and quite highly paid) softwaree engineer. He was given task to log every method in every controller in project he was working on. Engineer rewrote all controller methods, so from code like this:

    @RequestMapping(method = RequestMethod.GET)
    public String showEmployees(Model model) {
        List<Employee> employees = employeeDao.list();
        model.addAttribute('employees', employees);

        return 'employees/list';

he made following code:

    @RequestMapping(method = RequestMethod.GET)
    public String showEmployees(Model model) {
 LOGGER.log('Invoking method showEmployees');

        List<Employee> employees = employeeDao.list();
        model.addAttribute('employees', employees);

 LOGGER.log('Returning from method showEmployees');
        return 'employees/list';

What’s wrong with this code? Well:

  • It takes lot of time to alter every method with such code
  • It is error prone – you can introduce typos or forget to add logging somewhere
  • It is mixing cross-cutting concerns. That means you are adding same kind of repetetive, boilerplate and unrelated code to places where it doesn’t belong.
  • For example, what is the responsibility of showEmployees method? It is invoking service, getting employees and putting them to model. Logging really isn’t it’s responsibility, so why to mix those concerns?

    If engineer I mentioned knew about Aspect Oriented Programming he would save lot of time and made code better and more readable. Spring supports something called “Aspects” that are made exactly for such a problems. Aspects allow us to define common functionality in one place. Before we write any code, there is some terminology to understand. This terminology is quite huge and I am not going to write it here, but I encourage you to read Spring’s official reference page on AOP if you wish to know more. You should at least understand what is Advice, Join Point, Pointcut, Aspect and Weaving.

    OK let’s add Aspect for logging controller methods, exactly what should’ve done engineer from the story in the beginning.

    We must first add dependencies to pom.xml on AspectJ library:


    Also check if you have dependency on Spring’s AOP (but if you follow this tutorial from the very beginning you already have it):


    Now let’s write Aspect’s code. Create package org.timesheet.aspects and add ControllerLoggingAspect class:

    package org.timesheet.aspects;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import java.util.Arrays;
     * Will log every invokation of @RequestMapping annotated methods
     * in @Controller annotated beans.
    public class ControllerLoggingAspect {
        @Pointcut('within(@org.springframework.stereotype.Controller *)')
        public void controller() {}
        @Pointcut('execution(* *(..))')
        public void methodPointcut() {}
        @Pointcut('within(@org.springframework.web.bind.annotation.RequestMapping *)')
        public void requestMapping() {}
        @Before('controller() && methodPointcut() && requestMapping()')
        public void aroundControllerMethod(JoinPoint joinPoint) throws Throwable {
            System.out.println('Invoked: ' + niceName(joinPoint));
        @AfterReturning('controller() && methodPointcut() && requestMapping()')
        public void afterControllerMethod(JoinPoint joinPoint) {
            System.out.println('Finished: ' + niceName(joinPoint));
        private String niceName(JoinPoint joinPoint) {
            return joinPoint.getTarget().getClass()
                    + '#' + joinPoint.getSignature().getName()
                    + '\n\targs:' + Arrays.toString(joinPoint.getArgs());

    This code says, that @Before and @AfterReturning from controller method we will log information about it’s invokation (name and arguments). This advices execute when all three pointcuts are matching. controller() pointcut marks matching join point (that matches stereotype Controller) at which advice should be woven. methodPointcut() marks that we’re dealing with method call and requestMapping() pointcut marks methods annotated with @RequestMapping.

    To make it work, we’ll add aop.xml Spring configuration file under src/main/resources:

    <?xml version='1.0' encoding='UTF-8'?>
    <beans xmlns='http://www.springframework.org/schema/beans'
           xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:aop='http://www.springframework.org/schema/aop'
           xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd'>
        <!-- AOP support -->
        <bean id='controllerAspect' class='org.timesheet.aspects.ControllerLoggingAspect' />
            <aop:include name='controllerAspect' />

    And then we’ll import it in timesheet-servlet.xml Spring config:

    <import resource='classpath:aop.xml' />

    This was the last part of tutorial. I hope you have now better understanding of what Spring is and how does it help to solve your problems. Remember that we’ve covered only tiny piece of Spring in this tutorial. There is still much more to explore!

    Reference: Part 6 – Adding AOP support from our JCG partner Michal Vrtiak at the vrtoonjava blog.

    Michal Vrtiak

    Michal is a freelancer currently located in Prague, Czech Republic with huge passion for Java platform. He is very enthusiastic about Dependency Injection, IntelliJ IDEA and loves to use both Spring and Java EE.
    Notify of

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Newest Most Voted
    Inline Feedbacks
    View all comments
    10 years ago

    Hi I tried the same approach but it seems to give me a thread dump everytime . I am trying to wire up aop via spring mvc configuration annotation wise like below @Configuration @EnableWebMvc @EnableAspectJAutoProxy @ComponentScan({“com.pumpkinsafari.api”}) public class WebConfig extends WebMvcConfigurerAdapter { /** The Constant DD_MM_YYYY. */ private static final String DD_MM_YYYY = “yyyy-MM-dd”; /** The Constant DATE_FORMAT. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DD_MM_YYYY); /** * Instantiates a new web config. */ public WebConfig() { super(); } @Bean public RestControllerAspect controllerAspect(){ return new RestControllerAspect(); } // beans /** * Xstream marshaller. * * @return the x stream… Read more »

    7 years ago

    Just a reflexion. Seniority or youngster has nothing to do with low level of technical insigts.
    When I as a senior told the team to use AOP for this, I was told I was an idiot . . .

    best regards

    Back to top button