Home » Java » Enterprise Java » Spring – Adding AOP support

About Michal Vrtiak

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.

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:

            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>1.6.11</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjtools</artifactId>
                <version>1.6.11</version>
            </dependency>

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

      <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-aop</artifactId>
       <version>3.1.0.RELEASE</version>
      </dependency>

    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.
     */
    @Aspect
    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:aspectj-autoproxy>
            <aop:include name='controllerAspect' />
        </aop:aspectj-autoproxy>
    
    </beans>

    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.

    Do you want to know how to develop your skillset to become a Java Rockstar?

    Subscribe to our newsletter to start Rocking right now!

    To get you started we give you our best selling eBooks for FREE!

    1. JPA Mini Book

    2. JVM Troubleshooting Guide

    3. JUnit Tutorial for Unit Testing

    4. Java Annotations Tutorial

    5. Java Interview Questions

    6. Spring Interview Questions

    7. Android UI Design

    and many more ....

     

    One comment

    1. 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 marshaller
      */
      public XStreamMarshaller xstreamMarshaller() {
      final XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
      xStreamMarshaller.setAutodetectAnnotations(true);
      xStreamMarshaller.setAnnotatedClasses(new Class[] { Principal.class, Customer.class, Role.class,
      Privilege.class, SocialUser.class, SearchRequest.class });
      xStreamMarshaller.getXStream().addDefaultImplementation(java.sql.Timestamp.class, java.util.Date.class);

      return xStreamMarshaller;
      }

      /**
      * Marshalling http message converter.
      *
      * @return the marshalling http message converter
      */
      public MarshallingHttpMessageConverter marshallingHttpMessageConverter() {
      final MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
      final XStreamMarshaller xstreamMarshaller = xstreamMarshaller();
      marshallingHttpMessageConverter.setMarshaller(xstreamMarshaller);
      marshallingHttpMessageConverter.setUnmarshaller(xstreamMarshaller);

      return marshallingHttpMessageConverter;
      }

      // template

      /*
      * (non-Javadoc)
      *
      * @see
      * org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
      * #configureMessageConverters(java.util.List)
      */
      @Override
      public void configureMessageConverters(final List<HttpMessageConverter> messageConverters) {
      messageConverters.add(marshallingHttpMessageConverter());

      final ClassLoader classLoader = getClass().getClassLoader();
      if (ClassUtils.isPresent(“com.fasterxml.jackson.databind.ObjectMapper”, classLoader)) {
      MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
      jackson2HttpMessageConverter.getObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
      // Register date format for marshalling unmarshalling dates
      jackson2HttpMessageConverter.getObjectMapper().setDateFormat(DATE_FORMAT);
      messageConverters.add(jackson2HttpMessageConverter);
      } else if (ClassUtils.isPresent(“org.codehaus.jackson.map.ObjectMapper”, classLoader)) {
      MappingJacksonHttpMessageConverter jacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
      jacksonHttpMessageConverter.getObjectMapper().disable(
      DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
      // Register date format for marshalling unmarshalling dates
      jacksonHttpMessageConverter.getObjectMapper().setDateFormat(DATE_FORMAT);
      messageConverters.add(jacksonHttpMessageConverter);
      }

      super.configureMessageConverters(messageConverters);
      }

      }

      can u help

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *


    4 + = ten

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

    Want to take your Java Skills to the next level?
    Grab our programming books for FREE!
    • Save time by leveraging our field-tested solutions to common problems.
    • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
    • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
    Last Step ...

    Where should we send the free eBooks?

    Good Work!
    To download the books, please verify your email address by following the instructions found on the email we just sent you.