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:

  • Define aspect class.
  • Write methods containing the advice to be executed when method calls are intercepted.
  • 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.

We will create a class called AccessCheckAspect and place it in the aspect package. To establish that this is a configuration class, we will use the @Configuration annotation. We will also add the @Aspect annotation to establish that this class is related to AOP.

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