Monday, 29 April 2013

Spring AOP - Around Advice



Around advice
  • Around advice combination of all three advices i.e. beforeAdvice, AfterReturningAdvice and afterThrowing advice, and execute them corresponding to method execution.
  • Around Advice is not provided by spring framework.It is provided by AOP alliance as Open Source implementation.
  • We should implement an interface named MethodInterceptor and we have to override invoke () method in order to create a implementation class for Around advice. For the segregation of business logic from before and after advice services, in the middle we will call proceed () method.

 Syntax Of  AroundAdvice— invoke () Method
   public Object invoke(MethodInvocation methodInvocation) throws Throwable{                                           
              }


Steps for creating implementation for AroundAdvice :-


1) Create a java file in com.gaurav.aop.advices package and name it as TraceLogAroundMethodExecution.

2) Place the below code in that java file.

3) Create a java bean MovieService in the com.gaurav.aop.services package and place the below code in the bean file.

4) Create a xml bean file named spring-movie-service-beans-aroundadvice.xml inside src folder and place the below available code in that file

5) Create a java file TraceLogMethodAroundAdviceClient.java in the package com.gaurav.aop.advices.client inside src folder.Place the below available code in that file.



TraceLogAroundMethodExecution.java

package com.gaurav.aop.advices;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.transaction.IllegalTransactionStateException;

public class TraceLogAroundMethodExecution implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("Invoked Method name : "
                + methodInvocation.getMethod().getName());
        System.out.println("Invoked Method Parameters : "
                + Arrays.toString(methodInvocation.getArguments()));

        // Call for the before Advice
        System.out
                .println("~~~~~~~~~~ TraceLogAroundMethodExecution : Method beforeAdvice invoked ~~~~~~~~~~");

        try {
            // invoking the business method call
            Object result = methodInvocation.proceed();

            // Call for the AfterReturningAdvice
            System.out
                    .println("~~~~~~~~~~ TraceLogAroundMethodExecution : Method AfterReturningAdvice invoked ~~~~~~~~~~");

            return result;

        } catch (IllegalTransactionStateException e) {
            // Call for the afterThrowing advice.
            System.out
                    .println("~~~~~~~~~~ TraceLogAroundMethodExecution : Method afterThrowingAdvice invoked ~~~~~~~~~~");
              System.out.println("afterThrowingAdvice is invoked due to Execption :- "+e.getMessage());           
              throw e;
        }
    }

}

MovieService.java

package com.gaurav.aop.services;

import org.springframework.transaction.IllegalTransactionStateException;

public class MovieService {
    private String movieName;
    private String theatreName;
    private String theatreLocation;
    private String message;

    public void setMovieName(String movieName) {
        this.movieName = movieName;
    }

    public void setTheatreName(String theatreName) {
        this.theatreName = theatreName;
    }

    public void setTheatreLocation(String theatreLocation) {
        this.theatreLocation = theatreLocation;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void displayMovieName() {
        System.out.println("Movie Name : " + this.movieName);
    }

    public void displayTheatreName() {
        System.out.println("Theatre Name : " + this.theatreName);
    }

    public void displayTheatreLocation() {
        System.out.println("Theatre Location : " + this.theatreLocation);
    }

    public void throwError() {
        throw new IllegalTransactionStateException(message);
    }
}

spring-movie-service-beans-aroundadvice.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="movieService" class="com.gaurav.aop.services.MovieService">
        <property name="movieName" value="Titanic" />
        <property name="theatreName" value="Prasads IMAX" />
        <property name="theatreLocation" value="Necklace Road, Hyderabad" />
        <property name="message" value="movie ticket not found" />
    </bean>

    <bean id="traceLogAroundMethodBean" class="com.gaurav.aop.advices.TraceLogAroundMethodExecution" />

    <bean id="movieServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">

        <property name="target" ref="movieService" />

        <property name="interceptorNames">
            <list>
                <value>traceLogAroundMethodBean</value>
            </list>
        </property>
    </bean>
</beans>

TraceLogMethodAroundAdviceClient.java

package com.gaurav.aop.advices.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaurav.aop.services.MovieService;

public class TraceLogMethodAroundAdviceClient {
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "spring-movie-service-beans-aroundadvice.xml" });

        MovieService movieService = (MovieService) appContext
                .getBean("movieServiceProxy");

        System.out
                .println("\n##### Movie Name in client application is as below ");

        movieService.displayMovieName();

        System.out
                .println("\n\n##### Theatre Name in client application is as below ");

        movieService.displayTheatreName();

        System.out
                .println("\n\n##### Theatre Location in client application is as below ");

        movieService.displayTheatreLocation();

        try {
            System.out.println("\n\n");
            movieService.throwError();
        } catch (Exception e) {

        }

    }
}

Result:-




No comments:

Post a Comment