Spring AOP – @Before Advice Type

Facebooktwitterredditpinterestlinkedinmailby feather

Spring AOP – @Before Advice Type

As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology, and Advice is one of them. 

Advice: An action taken by an aspect at a particular join point is called Advice. In other words, an advice is an interceptor, retaining a chain of interceptors “around” the join point is called Advice. It represents the code that is executed by an aspect at a particular join point. There are three types of advice available in AOP: “around,” “before” and “after” advice.

Before Advice: It is executed before a method is invoked. Also, it is performed before a join point, but it cannot prevent the execution flow proceeding to the join point.

Here, we are using the @Before annotation for declaring a method as before advice.

Example of @Before Advice

Let’s understand the @Before advice type with the help of an example. In this example, we are going to create the following Java classes step by step:

  • Add Maven dependencies required in the project

Along with Spring dependencies, Spring AOP projects require one more dependency of AspectJ, which will be added inside the pom.xml.

Below is given the dependency of AspectJ:

pom.xml

  • Create the DAO class

In this step, we are going to create a DAO class named StudentAccountDao.java, that contains the actual business logic of the application.

StudentAccountDao.java

  • Create the Class that performs component scanning

In this step, we are going to create a class that performs component scanning. We use @EnableAspectJAutoProxy annotation that enables support for handling components marked as @Aspect.

DemoAOP.java

  • Create the Aspect class

In this step, we are going to create an aspect class named AspectClass that contains the aspect logic, such as all AOP advice types that are defined in this class.

AspectClass.java

  • Create the main class

In this step, we are going to create the main class named App.java that contains the main method.

App.java

Output

In the following output we can see that @Before advice is executed before executing the actual method.

@Before advice is executed
Facebooktwitterredditpinterestlinkedinmailby feather