Spring — AOP Q&A

Aspect-Oriented Programming (AOP) enables modularization of cross-cutting concerns. It complements Object-oriented programming (OOP). OOP has class and object as key elements but AOP has aspect as key element. Aspects allow you to modularize some functionality across the application at multiple points. This type of functionality is known as cross-cutting concerns.

  • Code tangling. Code tangling occurs when there is a mixing of cross-cutting concerns with the application’s business logic. It promotes tight coupling between the cross- cutting and business modules
  • Code scattering. This means that the same concern is spread across modules in the application. Code scattering promotes the duplicity of the concern’s code across the application modules

In any application, there is some generic functionality that is needed in many places. But this functionality is not related to the application’s business logic. Suppose you perform a role-based security check before every business method in your application. Here security is a cross- cutting concern.

Examples:

  • Logging and tracing
  • Transaction management
  • Security
  • Caching
  • Error handling
  • Performance monitoring
  • Custom business rules

Advice

Action taken by an aspect at a particular join point. Types:

  • Before —advice is executed first and then it calls the Target method
  • After — advice executed after the target method terminates by throwing any exception or normally
  • After-returning — advice is executed after the target returns successfully. This advice will never execute if target throws any exception in the application
  • After-throwing — advice is executed after the target throws an exception. This advice will never execute if the target doesn’t throw any exception in the application
  • Around — executed two times, first time it is executed before the advised method and second time it is executed after advised method is invoked.

Aspect

An aspect is the merger of advice and point-cuts. Taken together, advice and point-cuts define everything there is to know about an aspect — what it does and where and when it does it.

Join Point

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

Point-cut

A point-cut selects one or more join points out of the set of all join points in an application.

Weaving

Weaving is the process of applying aspects to a target object to create a new proxied object. The aspects are woven into the target object at the specified join points. The weaving can take place at several points in the target object’s lifetime:

  • Compile time
  • Class load time
  • Runtime

Spring AOP aspects are woven at Runtime.
If the advice throws an exception, target will not be called — this is a valid use of a Before Advice.

Spring uses proxy objects to implement the method invocation interception part of AOP. Such proxy objects wrap the original Spring bean and intercepts method invocations as specified by the set of point-cuts defined by the cross cutting concern.

Spring AOP uses two slightly different types of proxy techniques:

  • JDK dynamic proxies
  • CGLIB proxies

There is one limitation common to both proxy types:

  • Invocation of advised methods on self.

The Spring bean being proxied is not aware of the proxy and when a calling a method on itself, the proxy will not be invoked.

JDK Dynamic Proxies
Limitations of JDK dynamic proxies are:

  • Class for which a proxy is to be created must implement an interface
  • Only public methods in implemented interfaces will be proxied

CGLIB Proxies

Limitations of CGLIB proxies are:

  • Class for which a proxy is to be created must not be final
  • Method(s) in class for which a proxy is to be created must not be final
  • Only public methods will be proxied

Only public interface method calls for JDK Proxy and public methods for CGLIB.

  • @Before
  • @AfterReturning
  • @AfterThrowing
  • @After
  • @Around

What are they used for?

Before

Before advice will, as before, always proceed to the join point unless an execution is thrown from within the advice code. This makes it suitable for use-cases like:

  • Access control (security). Authorization can be implemented using before advice, throwing an exception if the current user is not authorized
  • Statistics. Counting the number of invocations of a join point

AfterReturning

After returning advice will, as before, be invoked after the execution of a join point has completed without throwing any exceptions. Examples of use-cases are:

  • Statistics. Counting the number of successful invocations of a join point.
  • Data validation. Validating the data produced by the advised method.

AfterThrowing

After throwing advice will, as before, be invoked after the execution of a join point that resulted in an exception being thrown. Examples of use-cases are:

  • Error handling. Some examples of error handling that can be implemented using after throwing advice are: Saving additional information connected to an error. Sending alerts when an error has occurred. Attempt error recovery.
  • Statistics. Counting the number of invocations of a join point that resulted in an exception being thrown. Counting the number of exceptions of a certain type being thrown.

After (Finally) Advice

After finally advice will, as before, be invoked after the execution of a join point regardless of whether the execution completed successfully or resulted in an exception being thrown. Possible use-cases for after finally advice are the same as for after returning and after throwing advice. An additional use-case for after (finally) advice is:

  • Releasing resources

As with finally-blocks in try-finally, the after (finally) advice is always executed after the completion of the join point and can thus ensure that resources are always released.

Around

Around advice is the most powerful of the advice types. The advice may select whether or not to execute the join point, catch an exception and throw another exception or not throw any exception at all etc. Around advice can be used for all of the use-cases for AOP.

Only around advice allows you to catch exceptions in an advice that occur during execution of a join point.

To enable detection of Spring beans implementing advice which implementation classes are annotated with the @Aspect annotation, the @EnableAspectJAutoProxy annotation should be applied to a @Configuration class. When using the @EnableAspectJAutoProxy annotation, the aspectjweaver.jar library from AspectJ needs to be on the classpath. In order for advice to be created from classes annotated with the @Aspect annotation, Spring beans need to be created from these classes. This can be accomplished in two ways:

  • Annotate advice classes with @Component. Thus advice classes should be annotated with both @Aspect and @Component. With component scanning enabled, advice classes will be auto-detected.
  • Create Spring beans from the advice classes. Use a regular method annotated with @Bean in a @Configuration class.

In Spring Boot Spring AOP works without @EnableAspectJAutoProxy. The @SpringBootApplication annotation contains the @EnableAutoConfiguration annotation. The auto configuration uses @Conditional type annotations (like @ConditionalOnClass and @ConditionalOnProperty) to scan the classpath and look for key classes that trigger the loading of ‘modules’ like AOP.

The @EnableAspectJAutoProxy annotation enables support for handling Spring beans that are annotated with AspectJ’s @Aspect annotation.

The following example shows the use of the ProceedingJoinPoint class as a parameter to an around advice. This type is used as the first parameter of a method implementing an around advice.
ProceedingJoinPoint is a subclass of JoinPoint.

An around advice is a special advice that can control when and if a method (or other join point) is executed.

This is the exact way the Spring EHCache Annotations project works, for example.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store