Around Advice Example Spring AOP

Around Advice Example Spring AOP

The same bean program of AOP Advices – Types – Tutorial is used. Change comes in configuration XML file and also slightly in client program. Let us name the modified XML file as applicationContext4.xml.

This is equivalent to all the three advices, Before advice, After returning advice and After Throwing Advice and executes before and after each bean method. Now add a new class AroundAdvice implementing MethodInterceptor interface and override the abstract method invoke(). You must call proceed() method to execute the original bean method; else the bean method is not called. Like this, the around advice can control the bean program execution. For this reason, around advice is used very often among all advices. Around Advice is represented by the interface MethodInterceptor. In this program, let us call all the advices (not only around advice).

1. The bean program used in AOP Advices – Types – Tutorial is used and reproduced here.

Bean Program – File Name:

Add a new class –

invoke() is a predefined abstract callback method of interface MethodInterceptor

Configuration file: applicationContext4.xml

Client Program:

Around Advice

The screenshot is very clutter as all the three print methods are called of bean program. Let us separate for one method, say printName(), and analyse the output.

See the bean code:

The getMethod().getName() of MethodInvocation parameter returns the name of the method which is invoked. It is here printName().

getArguments() method of MethodInvocation returns parameter list of printName() method. As there are no parameters, it printed empty, [].

The proceed() method calls the actual method printName() and printName() is executed and the output is printed.

"Around advice in action" is called before and also after calling printName() method (two times).

With this AOP theory and practice, I am sure you are well aware of the AOP terminology like joinpoint, concern, aspect, advice etc. Let us go more with pointcut, method matcher, StaticMethodMatcherPointcut etc. later.

Leave a Reply

Your email address will not be published. Required fields are marked *