Module 2: In-Depth Understanding of Spring AOP

hoangkimhoangkim
7 min read

Here are the questions and answers extracted in English from the provided files:

Question 01: What is the concept of AOP?

  • Answer: Aspect Oriented Programming (AOP) is a programming paradigm that complements Object-Oriented Programming (OOP) by providing a way to separate groups of cross-cutting concerns from business logic code. This is achieved by the ability to add additional behavior to the code without having to modify the code itself. This is achieved by specifying:

    • Location of the code which behavior should be altered (Pointcut is matched with Join point)

    • Code which should be executed that implements cross-cutting concern (Advice)

Problems AOP solves:

  • Allows proper implementation of Cross-Cutting Concerns

  • Solves Code Duplications by eliminating the need to repeat the code for functionalities across different layers, such functionalities may include logging, performance logging, monitoring, transactions, caching

  • Avoids mixing unrelated code, for example, mixing transaction logic code (commit, rollback) with business code makes code harder to read, by separating concerns code is easier to read, interpret, maintain

Three typical cross-cutting concerns:

  • Logging

  • Performance Logging

  • Caching

  • Security

  • Transactions

  • Monitoring

Two problems arise if cross-cutting concerns are not solved via AOP:

  • Code duplications: Before/After code duplicated in all locations where Advise would be applied, refactoring by extraction helps but does not fully solve the problem

  • Mixing of concerns: Business logic code mixed with logging, transactions, caching makes code hard to read and maintain

Question 02: What is a pointcut, a join point, an advice, an aspect, weaving?

  • Answer: Join Point: In aspect-oriented programming, a point in the execution of a program at which behavior can be altered by AOP. In Spring AOP, Join Point is always method execution.

    Pointcut: A predicate used to match join point. Additional code, called Advice, is executed at all parts of the program that match the pointcut. Spring uses the AspectJ pointcut expression language by default.

    Advice: Additional behavior that will be inserted into the code at each join point matched by pointcut.

    Aspect: Combines Pointcut and Advice. Usually represents a single behavior implemented by advice that will be added to all join points matched by pointcut.

    Weaving: The process of applying aspects, which modifies code behavior at join points that have matching pointcuts and associated advices. During weaving, aspects and application code are combined, which enables execution of cross-cutting concerns.

    Types of weaving:

    • Compile-Time Weaving: Bytecode is modified during compilation, aspects are applied, code is modified at join points matching pointcuts by applying advices

    • Load-Time Weaving: Bytecode is modified when classes are loaded by class loaders, during class loading aspects are applied, code is modified at join points matching pointcuts by applying advices

    • Runtime Weaving: Used by Spring AOP, for each object/bean subject to aspects, a proxy object is created (JDK Proxy or CGLIB Proxy), proxy objects are used instead of the original object, at each join point matching pointcut, method invocation is changed to apply code from advice

Question 03: How does Spring solve (implement) a cross-cutting concern?

  • Answer: Spring implements cross-cutting concerns using the Spring AOP module. Spring AOP uses AspectJ expression syntax for Pointcut expressions, which are matched against Join Point, code is altered with logic implemented in advices. In Spring AOP, Join Point is always method invocation.

    Spring AOP uses Runtime Weaving, and for each type subject to aspects, to intercept calls, spring creates one type of proxy:

    • JDK Proxy: Created for classes that implement an interface

    • CGLIB Proxy: Created for classes that are not implementing any interface

Question 04: Which are the limitations of the two proxy-types?

  • Answer: JDK Dynamic Proxy Limitations:

    • Does not support self-invocation

    • Class must implement an interface

    • Only methods implementing the interface will be proxied

CGLIB Proxy Limitations:

  • Does not support self-invocation

  • Class for which proxy should be created cannot be final

  • Method which should be proxied cannot be final

  • Only public/protected/package methods will be proxied, private methods are not proxied

Visibility of Spring Bean methods to be proxied:

  • JDK Dynamic Proxy: Public

  • CGLIB Proxy: Public/protected/package

Question 05: How many advice types does Spring support? Can you name each one?

  • Answer: Spring supports the following advice types:

    • @Before: Executed before the join point matched by pointcut is executed

    • @After: Executed after the join point matched by pointcut is executed

    • @AfterThrowing: Executed when an exception is thrown from the join point matched by pointcut

    • @AfterReturning: Executed after the join point matched by pointcut is executed successfully without any exception

    • @Around: Allows you to take full control over the join point matched by pointcut, the most powerful advice, allows you to implement all advices from above, you need to call ProceedingJoinPoint::proceed() to execute the original code

Examples of usage:

  • @Before: Authorization, Security, Logging, Data Validation

  • @After: Logging, Resource Cleanup

  • @AfterThrowing: Logging, Error Handling

  • @AfterReturning: Logging, Data Validation for method result

  • @Around: Transactions, Distributed Call Tracing, Authorization, Security

Two advices that can be used to catch and handle exceptions:

  • @AfterThrowing: With the throwing field set and exception passed as an argument

  • @Around: With try ... catch block implemented

Question 06: What do you have to do to enable the detection of the @Aspect annotation? What does @EnableAspectJAutoProxy do?

  • Answer: To enable detection of @Aspect annotation, you need to:

    • Have a @Configuration class with @EnableAspectJAutoProxy

    • Have beans for @Aspect annotated classes created

    • Use @ComponentScan with @Component at the class annotated with @Aspect

    • Use @Bean in the Configuration class and create Spring Aspect Bean manually

    • Have aspectjweaver/spring-aop on the classpath

Annotation @EnableAspectJAutoProxy enables detection of @Aspect classes and creates proxy objects for beans subject to aspects. Internally, the process of creating proxies is done by AnnotationAwareAspectJAutoProxyCreator. By creating a proxy for each bean subject to aspects, Spring intercepts the calls and implements Before / After / AfterReturning / AfterThrowing / Around advices.

Question 07: If shown pointcut expressions, would you understand them?

  • Answer: Pointcut designator types supported by Spring AOP:

    • execution: Matches method execution

    • within: Matches execution within the specified class/classes

    • args: Matches execution of method with matching arguments

    • bean: Matches execution of method with matching Spring Bean name

    • this: Matches execution against the type of proxy that was generated by Spring AOP

    • target: Matches execution against the type of the target object invoked by proxy

    • @annotation: Matches method execution annotated with the specified annotation

    • @args: Matches method execution with argument types annotated with the specified annotation type

    • @within: Matches method executions inside classes annotated with the specified annotation

    • @target: Matches method executions inside proxied target class annotated with a specific annotation

Pointcut expression to match both getter and setter methods:

    execution(* com.beans.EmployeeBean.get*()) || 
    execution(* com.beans.EmployeeBean.set*(*))

Question 08: What is the JoinPoint argument used for?

  • Answer: JoinPoint is an object that can be used to retrieve additional information about the join point during execution. JoinPoint needs to be the first parameter of Advice, only in that case, Spring Framework will inject JoinPoint into the advice method.

    Join Point is supported in the following advice types:

    • Before

    • After

    • After Returning

    • After Throwing

Examples of information that can be retrieved from JoinPoint:

  • String representation of Join Point

  • Arguments of Join Point (e.g., Method Arguments)

  • Signature of Join Point (e.g., Method Signature)

  • Kind/Type of Join Point

  • Target/This object being proxied

Question 09: What is a ProceedingJoinPoint? When is it used?

  • Answer: ProceedingJoinPoint is an object that can be provided to @Around advice as the first argument, it is a type of JoinPoint which can be used to change method arguments during method execution at runtime or block the execution of the original method entirely.

    ProceedingJoinPoint is used in @Around advice, it contains all methods from JoinPoint and also adds:

    • proceed: Executes the original method

    • proceed(args): Executes the original method with the provided arguments

ProceedingJoinPoint can be used in the following use cases:

  • Conditionally block method execution

  • Filter arguments

  • Inject additional argument

0
Subscribe to my newsletter

Read articles from hoangkim directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

hoangkim
hoangkim