Defining an Aspect

Learn how to define an aspect and intercept message calls.

In this lesson, we will define an aspect to intercept all the calls to the business layer and log their output. We will create a number of aspects and place all of them in a separate package.

When we intercept method calls, we have the option to perform tasks before the method is executed as well as afterwards. To define an aspect for a cross-cutting concern, we will perform the following steps:

  1. Define aspect class.

  2. Write methods containing the advice to be executed when method calls are intercepted.

  3. Write pointcut expressions for intercepting method calls.

Aspect

Suppose we want to intercept method calls to check if the user has access before the method gets executed. Access check is a cross-cutting concern and instead of implementing it in every method, we can write it as an aspect.

To keep the code organized, create a package aspect in io.datajek.springaop.movierecommenderaop package.

In the aspect package, we will create a class named AccessCheckAspect. This class is a configuration entity, so we mark it with the @Configuration annotation. We will also add the @Aspect annotation to signify its AOP-related functionality.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.