Monday, 29 April 2013

Spring AOP - Before Advice


Before Advice

  • We should implement MethodBeforeAdvice interface and override before(Method method, Object[] arg, Object target) method in order to create before advice implementation class.

  • MethodBeforeAdvice interface is available in org.springframework.aop.* package.

  • This advice allows us to execute services which are required to be applied before business logic execution.

  • These services will be executed only at run time.

Syntax Of  MethodBeforeAdvice before() Method

public void before(Method method, Object[] arg, Object target)
                                                throws Throwable {
                                }
  • The first parameter Method method of before() method  is a class belongs to reflection package  and by using this parameter  we can get the name of the business method, through getName() method.
  • Second parameter object [] is used to access the parameter values of the business method, the parameters of business method are stored in object array and those parameters are given to before () method by the container in the form of objects only.
  • The third parameter is an object to which this service will be going to apply; usually this will take care by container.
  • The service implemented in before advice will be called from a proxy class which is generated by the container for a target object.

Steps for implementing MethodBeforeAdvice

1) Create a java project using eclipse.

2) Create three packages and name it as com.gaurav.aop.advices, com.gaurav.aop.advices.client and com.gaurav.aop.services inside src folder.

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

4) Place the below code in that java file.

TraceLogBeforeMethodExecution.java 

package com.gaurav.aop.advices;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class TraceLogBeforeMethodExecution implements MethodBeforeAdvice {

    @Override
    public void before(Method method, Object[] arg, Object target)
            throws Throwable {
        System.out
                .println("TraceLogBeforeMethodExecution:- Method before advice execution");
        System.out.println("\n The method which is going to execute is - "
                + method.getName());

    }

}

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

InternetUser.java

package com.gaurav.aop.services;

import org.springframework.transaction.IllegalTransactionStateException;

public class InternetUser {
    private int userId;
    private String internetUserName;
    private String productPurchased;
    private String transactionStatus;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getInternetUserName() {
        return internetUserName;
    }

    public void setInternetUserName(String internetUserName) {
        this.internetUserName = internetUserName;
    }

    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 void getException() {
        throw new IllegalTransactionStateException(internetUserName);
    }

}

6) Create a xml bean file inside src folder and place the below code in that file

spring-internet-user-beans-beforeadvice.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="internetUser" class="com.gaurav.aop.services.InternetUser">
        <property name="userId" value="11156" />
        <property name="internetUserName" value="Kumar Gaurav" />
        <property name="productPurchased" value="Sony Bravia" />
        <property name="transactionStatus" value="success" />
    </bean>

    <bean id="traceLogBeforeMethodBean" class="com.gaurav.aop.advices.TraceLogBeforeMethodExecution" />

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

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

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

 "target" – Define which bean we want to steal/hijack.
 "interceptorNames" – Define which advice,  we want to apply on this proxy /target object.

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

TraceLogMethodBeforeAdviceClient.java

package com.gaurav.aop.advices.client;

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

import com.gaurav.aop.services.InternetUser;

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

        InternetUser internetUser = (InternetUser) appContext
                .getBean("internetUserProxy");

        System.out.println("##### InternetUser ID is:-  "
                + internetUser.getUserId() + "\n");

        System.out.println("##### InternetUser Name is:-  "
                + internetUser.getInternetUserName() + "\n");

        System.out.println("##### Product purchased by InternetUser is :-  "
                + internetUser.getProductPurchased() + "\n");

        System.out.println("##### Product purchased transaction status is :-  "
                + internetUser.getTransactionStatus() + "\n");

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

        }

    }
}



Result:-
  

No comments:

Post a Comment