In this blog, let us talk about Around Advice. There are some few points about it.
Around Advice is combination of Before Advice and After Advice.
In a single Around Advice we can implement both before and after services.
Note, Around Advice is not given by spring framework, it is from Open Source implementation called AOP alliance.
Around Advice can be used by any framework which supports AOP.
Around Advice can access the return value of business method and it can modify the value and it can return a different value back to the client, as return type is Object, but in the After Advice its not possible right, as its return type is void.
In order to create Around Advice, we should implement an interface called MethodInterceptor and override the method called invoke which has a prarameter MethodInvocation type. We can use this parameter to invoke our business logic method like methodInvoation.proceed(). And we can add our before services before this code execution and put after services after this code.
@Override public Object invoke(MethodInvocation invocation)throws Throwable { // Adding before service in here. invocation.proceed(); // Adding after service in here. // we can change the return value we want via below return codes. returnnull; }
}
In above codes, we can see that we put the before services before the proceed() method and put the after services after it. and we can change the return value of the logic method.
So now let us to see a full expample.
MyLogicInterface.java
1 2 3 4 5 6
package spring.test.aop;
publicinterfaceMyLogicInterface { intadd(int a, int b); }
// changed the return value to 0 when the second parameter is less than 0. if (secondParam < 0) return0;
returnnull; }
}
In this our around advice. we print the method description in our before service and changed the return value to 0 when the second parameter is less than 0 in after service.
publicstaticvoidmain(String[] args) { applicationContext = newClassPathXmlApplicationContext("springConfig.xml"); MyLogicInterfacelogicInterface= (MyLogicInterface)applicationContext.getBean("proxyFactoryBean"); intresult1= logicInterface.add(1, 10); System.out.println(String.format("After Advice - The result is: %s \n", result1)); intresult2= logicInterface.add(1, -10); System.out.println(String.format("After Advice - The result is: %s", result2)); }
}
You will notice that we pass -10 to second parameter in second times method called. Let’s see the result:
Before Services : add(1, 10)
The internal result of 1 + 10 is: 11
After Advice - The result is: 11
Before Services : add(1, -10)
The internal result of 1 + -10 is: -9
After Advice - The result is: 0
You see, the internal result is -9, but after service, the result is changed to 0. So the return value is changed by our Around Advice.
Note again: The Around Advice can change the return value of business logic method, but After Advice cannot.