Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AOP and Proxy: Behind the scene of Spring Data

AOP and Proxy: Behind the scene of Spring Data

Mitsunori Komatsu

April 24, 2023
Tweet

More Decks by Mitsunori Komatsu

Other Decks in Programming

Transcript

  1. Query Methods in Spring Data JDBC is very useful! Great!

    But how does it work? SELECT * FROM users WHERE name LIKE ‘%${name}%’ ORDER BY id DESC LIMIT 3
  2. What is Proxy in Spring? <<interface>> org.springframework.aop.framework.AopProxy org.springframework.aop.framework. JdkDynamicAopProxy -

    Internally uses java.lang.reflect.Proxy org.springframework.aop.framework. CglibAopProxy - Internally uses CGLIB (byte code gen library) What is AOP…?
  3. - Aspect-oriented programming (AOP) is a programming paradigm that aims

    to increase modularity by allowing the separation of cross-cutting concerns - This allows behaviors that are not central to the business logic to be added to a program without cluttering the code core to the functionality - For instance, - Logging - Retry - Authorization Retry AccountServi ce.transfer OrderService .placeOrder StorageServi ce.addItem What is AOP? Logging before-state Authorization Logging before-state Business logics AOP actions These explanations are copied from Wikipedia, right?
  4. Aspect The terminology of AOP Join point: account.getId() Method calls,

    field accesses and object instantiations. Spring AOP supports only Method calls Pointcut Predicates that match join points Program execution Advice is associated with a pointcut expression and runs at any join point matched by the pointcut Join point: user.age = 42 Join point: group.setName(x) Join point: item.setPrice(p) In the following example, - MyAspect is Aspect - @Before(“execution(...)”) is Pointcut - logValues() is Advice @Aspect public class MyAspect { @Before("execution(* set*(..))") public void logValues() { ... } } Advice An action taken by an aspect at a particular join point. Different types of advice include "around", "before", and "after" advice This Pointcut means - The execution of any method with a name that begins with set OK. But how Proxy is used in AOP…?
  5. AOP in Spring AOP engines in Spring Spring AOP Supported

    Join Points: - Method execution AspectJ Supported Join Points: - Method execution - Field access - Object instantiation - etc. CGLIB based Proxy - Use CGLIB (byte code generation library) - Support interface/class JDK based Proxy - Use java.lang.reflect.Proxy - Support only interface AOP interfaces in Spring AspectJ style - Annotation based - Compatible with AspectJ class ProxyFactory - Create a proxy instance programmatically
  6. Example: Query Method-ish Proxy using ProxyFactory This class is a

    delegate for other method calls Advice Ugly manual Pointcut… Calculate a return value