Spring AOP Example Before and After Advice XML

By | 2017-01-17T13:39:19+05:30 May 8th, 2016|Spring|

In this tutorial, we are going to implement Spring AOP Example for Advices. Advices are the actual implementations of Aspects. In the previous tutorial we had a long discussion about what is AOP Framework and AOP Terminologies ?

Before Advice :

Before advice is a method that gets executed before a join point. So, irrespective of whether your join point successfully completes or throws exception Before advice method gets executed.

Key points to remember :

[tie_list type=”checklist”]

  • Before Advice is executed before actual method call.
  • Similar to other advices, Spring container maps their execution during run time, and not while compilation.
  • Before Advice has to be a class implementing MethodBeforeAdvice interface.
  • Keep our logic to be executed before join point method in implemented before() method.
  • Below are the list of arguments present in before() and their types and significance;
    Syntax:
    public void before(Method m,Object args[], Object target)throws Exception
    Explaination
    Method m: Object of java.lang.reflect.Method class, and access the join point method name using m.getName()
    Object args[]: Array of arguments passed to the join point method
    Object target: Object of service class, where the join point method is defined

[/tie_list]

After Advice:

After advice is a method that gets executed after a join point. This advice gets executed irrespective of join point method whether successfully executed or failed with a run time exception. If the join point method has a return statement, After advice method it will be executed after returning the value, unlike finally block in java, just before returning the value.

Key points to remember :

[tie_list type=”checklist”]

  • After Advice is executed after actual method call
  • Similar to other advices, Spring container maps their execution during run time, and not while compilation
  • After Advice has to be a class implementing AfterReturningAdvice interface
  • Keep our logic to be executed after join point method in implemented afterReturning() method.
  • Below are the list of arguments present in before() and their types and significance
    Syntax:
    public void afterReturning(Method m,Object args[], Object target)throws Exception
    Explanation :
    Method m: Object of java.lang.reflect.Method class, and access the join point method name using m.getName()
    Object args[]: Array of arguments passed to the join point method
    Object target: Object of service class, where the join point method is defined

[/tie_list]

Steps to implement before and after advice:

  • BeforeAdvice Implementation
    a. Create a class where you want to have a method to be called before actual method call and have the class implementing org.springframework.aop.MethodBeforeAdvice;
    b. Since you have implemented interface, override the interface method before()
    c. This method has arguments listed above, so write your method body as what you want to do before execution of actual join point method
  • AfterAdvice Implementation
    a. Create a class where you want to have a method to be called after method completion and have the class implementing org.springframework.aop.AfterReturningAdvice;
    b. Since you have implemented interface, override the interface method afterReturning()
    c. This method has arguments listed above, so write your method body as what you want to do after successful/ exception scenarios of actual join point method
  • Target Object :
    a. Create Service class, and add business methods to it
  • Spring Config file :
    Create a bean for the Throws Advice implementations as below: [box type=”shadow” align=”alignleft” class=”” width=”100%”] <bean id=”beforeAdvice” class=”com.spring.aop.advices.BeforeAdvice” />
    <bean id=”afterAdvice” class=”com.spring.aop.advices.AfterAdvice” /> [/box]
  • Create a bean for Target object as below: [box type=”shadow” align=”alignleft” class=”” width=”100%”]
    <bean id=”product” class=”com.spring.aop.Product”>
    <property name=”productId” value=”101″ />
    <property name=”productName” value=”iPhone” />
    </bean>[/box]
  • Create a bean for org.springframework.aop.framework.ProxyFactoryBean and pass properties like target with you target bean id, proxyInterfaces with class path of interface your target bean implemented, and interceptorNames with bean ids of advice as shown below:[box type=”shadow” align=”alignleft” class=”” width=”100%”]
    <bean id=”productProxy” class=”org.springframework.aop.framework.ProxyFactoryBean”>
    <property name=”target” ref=”product” />
    <property name=”proxyInterfaces” value=”com.spring.aop.BaseProducts” />
    <property name=”interceptorNames”>
    <list>
    <value>afterAdvice</value>
    <value>beforeAdvice</value>
    </list>
    </property>
    </bean>[/box]

Here we are going to make the theory in practical with respect to the AOP Advices.

Spring AOP Example for Before and After Advice :

Project Structure :

Spring AOP Example

Create Product Interface :

BaseProducts.java


package com.spring.aop;

public interface BaseProducts {
    int productId = 0;
    String productName = "";

    void buyProduct();

    void sellProduct();
}

Create Product which implements the BaseProducts interface.

Product.java


package com.spring.aop;

public class Product implements BaseProducts {
    private int productId;
    private String productName;

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public void buyProduct() {

        System.out.println("I am buying the Product : " + getProductName());
    }

    public void sellProduct() {

        System.out.println("I am Selling the Product : " + getProductName());

    }
}

Create BeforeAdvice by implementing the MethodBeforeAdvice. It will execute before the method execution.

BeforeAdvice.java

package com.spring.aop.advices; 
 
import java.lang.reflect.Method; 
 
import org.springframework.aop.MethodBeforeAdvice; 
 
public class BeforeAdvice implements MethodBeforeAdvice { 
 
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { 
        // TODO Auto-generated method stub 
        System.out.println("Beginning "); 
    } 

} 

Create AfterAdvice class by implementing the AfterReturningAdvice interface. It will execute after the method execution.

AfterAdvice.java


package com.spring.aop.advices;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterAdvice implements AfterReturningAdvice {

    public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("Completed ");
    }
}

Configuration for Spring AOP Advices :

Configure the necessary bean configurations here such as BeforeAdvice, AfterAdvice and Proxy .

spring-congiguration.xml


<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="product" class="com.spring.aop.Product">
        <property name="productId" value="101" />
        <property name="productName" value="iPhone" />
    </bean>
    <bean id="beforeAdvice" class="com.spring.aop.advices.BeforeAdvice" />
    <bean id="afterAdvice" class="com.spring.aop.advices.AfterAdvice" />
    <bean id="productProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="product" />
        <property name="proxyInterfaces" value="com.spring.aop.BaseProducts" />
        <property name="interceptorNames">
            <list>
                <value>afterAdvice</value>
                <value>beforeAdvice</value>
            </list>
        </property>
    </bean>
</beans>

On the above configuration file, we have configured the below.[tie_list type=”checklist”]

  • Creating a Product bean with values.
  • Creating a BeforeAdvice bean.
  • Creating a AfterAdvice bean.
  • Creating the ProxyFactoryBean : ProxyFactoryBean is a class which is given by Spring framework
    It will create a proxy object at runtime.
  • ProxyFactoryBean is a factory class, it is responsible to produce the proxy class objects at runtime.
  • To configure the ProxyFactoryBean class, we need to pass the below 3 properties.
    Proxy Interfaces : We need to pass the proxy interface to it. In our case it is BaseProducts.java.
    Interceptor names : We need to pass ids of advice classes or advisors. In our case, BeforeAdvice.java and AfterAdvice.java.
    Target : We need to pass a reference of a business class id. In our case business class is Product.java

[/tie_list]

I hope, this is clear guys 🙂 isn’t it .? Then it is the time to run the application.

Run the application :

Main.java


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

import com.spring.aop.BaseProducts;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/application-config.xml");
        BaseProducts product = (BaseProducts)context.getBean("productProxy");
        
        System.out.println("**********");
        product.sellProduct();
        System.out.println("**********");
        product.buyProduct();
        System.out.println("**********");
    }

}

Output :

[box type=”success” align=”alignleft” class=”” width=”100%”]

**********
Beginning
I am Selling the Product : iPhone
Completed
**********
Beginning
I am buying the Product : iPhone
Completed
**********

[/box]

 

Download Example

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment