Skip to content

AOP Example

Vishnu Garg edited this page Aug 3, 2018 · 2 revisions

AOP Example based on XML based configurations

AOP Proxies Example

  • Spring AOP is proxy-based. It is vitally important that you grasp the semantics of what that last statement actually means before your write own aspects or use any of the Spring AOP-based aspects supplied with the Spring Framework.
  • Consider first the scenario where you have a un-proxied, straight object reference—nothing special about it, plain vanilla, as illustrated by the following code:
public class SamplePojo implements Pojo 
{
    public void foo() {
        this.bar();
    }
    public void bar() {
        // some logic...
    }
}

Things change slightly when the reference to that client code is a proxy.

public class AOPProxyExample {
	public static void main(String[] args) {

		ProxyFactory factory = new ProxyFactory(new SamplePojo());

		factory.addInterface(Pojo.class);
	       // Advice is being added here
		factory.addAdvice(new BeforeMethod());
		Pojo pojo = (Pojo) factory.getProxy();
		pojo.foo();
	}
}
  • The key thing to understand here is that the client code inside the main (...) method of the Main class has a reference to the proxy. This means method calls on that object reference will be calls on the proxy, and as such the proxy will be able to delegate to all the interceptors (advice) that are relevant to the particular method call.
  • Once the call has finally reached the target object reference, the SamplePojo object reference in this case, any method calls that it may make on itself, such as this.bar() or this.foo(), are to be invoked against this reference, and not that proxy. This has important implications.

Spring AOP Example

1. Create an Advice

1.1 Create AOP Service on which Advice is added. In AOP the advice is an action taken before or after method execution. There are different types of advice such as before, after, around, after-returning and after-throwing advice. Below all types advice and create an example of each them.

public class SampleService{
	private String name;
	private int id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void printDetails() {
		System.out.println(
				"AOPAdvice : Method printDetails() : My name is " + name + "         and my id is " + id);
	}

	public void checkName() {
		if (name.length() < 15) {
			throw new IllegalArgumentException();
		}
	}

	public void sayHello(String message) {
		System.out.println("AOPAdvice : Method sayHello() : Hello.. " + message);
	}
}

1.2 Create Advice

  • 1. Before Advice : This advice runs before the execution of Join point methods, but doesn't have to prevent execution flow proceeding to method execution.
  • 2. After Returning Advice
  • 3. ThrowsAdvice : AfterThrowingException
  • 4 Around Advice Here I am creating all advice in one class, can also be created separately If all the advice are added then its the sequence
  • It Call Around Advice
  • Before Advice call
  • Actual method is executed
  • After Advice/Throw Exception Advice
  • Around Advice /Around Advice Exception Throw
public class AOPAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice, MethodInterceptor {

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("===SPRING AOP=== AfterReturningMethod : Execute after return method ");
	}

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("===SPRING AOP=== BeforeMethod : Execute before method!");
	}

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		System.out.println("===SPRING AOP=== AroundMethod: Method name : " + methodInvocation.getMethod().getName());
		System.out.println(
				"===SPRING AOP=== AroundMethod: Method arguments :" + Arrays.toString(methodInvocation.getArguments()));
		System.out.println("===SPRING AOP=== AroundMethod: Before method execute");
		try {
			Object result = methodInvocation.proceed();
			System.out.println("===SPRING AOP=== AroundMethod: After method execute");
			return result;
		} catch (IllegalArgumentException e) {
			// same with ThrowsAdvice
			System.out.println("===SPRING AOP=== AroundMethod: When method exception throws ");
			throw e;
		}
	}

	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println("===SPRING AOP=== AfterThrowingExceptionMethod : Execute when method throws exception");
	}
}

aop_example.xml looks like, If you are creating separate beans for different advice need to pass them in list option, like done is example.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
    <bean id="sampleServiceBean" class="com.spring.revisited.xml.aop.SampleService">
        <property name="name" value="How are you ?" />
        <property name="id" value="456123" />
    </bean>
    <bean id="aopAdviceBean"
        class="com.spring.revisited.xml.aop.AOPService" />
    <bean id="sampleServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="sampleServiceBean" />
        <property name="interceptorNames">
            <list>
                <value>aopAdviceBean</value>
            </list>
        </property>
    </bean>
</beans>

AOPExample.java

public class AOPExample {
	public static void main(String[] args) {
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("aop_example.xml");
        SampleService sampleService = (SampleService) context.getBean("sampleServiceProxy");
        
        sampleService.printDetails();
        try{
            sampleService.checkName();
        } catch(Exception e){
            System.out.println("SampleService: Method checkName() thrown exception");
        }
        sampleService.sayHello("JavaTutorials");
        context.close();
	}
}
Clone this wiki locally