Spring Boot AOP Around Advice

Around advice is represented by @Around annotation. It executes before and after a join point. It is the most powerful advice. It also provides more control for end-user to get deal with ProceedingJoinPoint.

Let's implement around advice in an application.

Spring Boot Around Advice Example

Step 1: Open Spring Initializr http://start.spring.io.

Step 2: Provide the Group name. We have provided the Group name com.javatpoint.

Step 3: Provide the Artifact Id. We have provided the Artifact Id aop-around-advice-example.

Step 4: Add the Spring Web dependency.

Step 5: Click on the Generate button. When we click on the Generate button, it wraps all the specifications in a jar file and downloads it to the local system.

Spring Boot AOP Around Advice

Step 6: Extract the downloaded jar file.

Step 7: Import the folder by using the following steps:

File -> Import -> Existing Maven Projects -> Next -> Browse the Folder aop-around-advice-example -> Finish.

Step 8: Open the pom.xml file and add the following AOP dependency. It is a starter for aspect-oriented programming with Spring AOP and AspectJ.

pom.xml

Step 9: Create a package with the name com.javatpoint.service.

Step 10: Create a class in the above package with the name BankService.

In this class, we have defined a method named displayBalance(). It checks the account number. If the account number is matched returns total amount, else returns a message.

BankService.java

Step 11: Create another package with the name com.javatpoint.aspect.

Step 12: Create a class in the above package with the name BankAspect.

In the following class, we have defined two methods named logDisplayingBalance() and aroundAdvice() method.

BankAspect.java

Step 13: Open AopAroundAdviceExampleApplication.java file and add an annotation @EnableAspectJAutoProxy.

The annotation enables support for handling components marked with AspectJ's @Aspect annotation. It is used with @Configuration annotation.

ConfigurableApplicationContext is an interface that provides facilities to configure an application context in addition to the application context client methods in the ApplicationContext.

AopAroundAdviceExampleApplication.java

After creating all the packages and classes the project directory looks like the following:

Spring Boot AOP Around Advice

Now, run the application.

Step 14: Open the AopAroundAdviceExampleApplication.java and run it as Java Application.

Spring Boot AOP Around Advice

In the above output, we see that the method aroundAdvice() invokes two times. First, before the execution of the displayBalance() method and second, after the execution of the displayBalance() method. It is called around advice.







Latest Courses