Showing posts with label Spring-AOP. Show all posts
Showing posts with label Spring-AOP. Show all posts

Monday, 29 April 2013

Spring AOP - Throws Advice



After throwing advice
  • AfterThrowing advice will execute after the method throws an exception.
We should implement ThrowsAdvice interface. As this interface is a tag interface (marker interface) for throws advice means no methods are available in this interface as methods are invoked by reflection. So, Implementing classes must implement method of the below form:

              void afterThrowing([Method, args, target], ThrowableSubclass);

·         Some examples of valid methods are:-
          public void afterThrowing(Exception ex)
          public void afterThrowing(RemoteException)
          public void afterThrowing(Method method, Object[] args, Object target, Exception ex)

  • If a throws-advice method throws an exception itself, it will override the original exception (i.e. change the exception thrown to the user). The overriding exception will typically be a RuntimeException; this is compatible with any method signature

 Syntax Of  ThrowsAdvice— afterThrowing () Method

public void afterThrowing(IllegalTransactionStateException itse)
                                                throws Throwable {
                }


Steps for creating implementation for ThrowsAdvice :-




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

2) Place the below code in that java file.

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

4) Create a xml bean file named spring-user-transaction-beans-afterthrows.xml inside src folder and place the below code in that file

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


TraceLogAfterMethodThrowException.java

package com.gaurav.aop.advices;

import org.springframework.aop.ThrowsAdvice;
import org.springframework.transaction.IllegalTransactionStateException;

public class TraceLogAfterMethodThrowException implements ThrowsAdvice {
    public void afterThrowing(IllegalTransactionStateException itse)
            throws Throwable {
        System.out
                .println("TraceLogAfterMethodThrowException:- Entered after method throws exception ");
        System.out.println("Execption is - " + itse.getMessage());
    }
}

UserTransaction.java

package com.gaurav.aop.services;

import org.springframework.transaction.IllegalTransactionStateException;

public class UserTransaction {
    private Long transactionId;
    private String userName;
    private String productPurchased;
    private String transactionStatus;
    private String message;

    public Long getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(Long transactionId) {
        this.transactionId = transactionId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getProductPurchased() {
        return productPurchased;
    }

    public void setProductPurchased(String productPurchased) {
        this.productPurchased = productPurchased;
    }

    public String getTransactionStatus() {
        return transactionStatus;
    }

    public void setTransactionStatus(String transactionStatus) {
        this.transactionStatus = transactionStatus;
    }

    public String getMessage() {
        return message;
    }

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

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

}

spring-user-transaction-beans-afterthrows.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="userTransaction" class="com.gaurav.aop.services.UserTransaction">
       
        <property name="transactionId" value="145678622322" />
        <property name="userName" value="Kumar Gaurav" />
        <property name="productPurchased" value="Galaxy S4" />
        <property name="transactionStatus" value="Failed" />
        <property name="message" value="Failed due to IllegalTransactionStateException" />
    </bean>

    <bean id="traceLogAfterMethodThrowExceptionBean"
        class="com.gaurav.aop.advices.TraceLogAfterMethodThrowException" />

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

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

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

TraceLogMethodThrowsAdviceClient.java

package com.gaurav.aop.advices.client;

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

import com.gaurav.aop.services.UserTransaction;

public class TraceLogMethodThrowsAdviceClient{
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "spring-user-transaction-beans-afterthrows.xml" });

        UserTransaction userTransaction = (UserTransaction) appContext
                .getBean("userTransactionProxy");

        System.out
                .println(" ##### InternetUser ID in client application is:-  "
                        + userTransaction.getTransactionId() + "\n");

        System.out
                .println(" ##### InternetUser Name in client application is:-  "
                        + userTransaction.getUserName() + "\n");

        System.out
                .println(" ##### Product tried to purchase by InternetUser in client application is :-  "
                        + userTransaction.getProductPurchased() + "\n");

        System.out
                .println(" ##### Transaction status in client application is :-  "
                        + userTransaction.getTransactionStatus() + "\n");

        try {
            userTransaction.getException();
        } catch (Exception e) {

        }

    }
}

Result:-



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:-