Proxy Design Pattern Using Spring AOP
Proxy design pattern provides an object of a class with the functionality of another class with having it. This pattern comes under the structural design pattern of GOF Design Patterns.
Spring provides two ways to create the proxy in the application.
1.JDK
2.CGLIB
JDK proxy CGLIB proxy
1) Also called dynamic proxies 1) NOT built into JDK
2) API is built into the JDK 2) Included in Spring JARs
3) Requirements: Java interface(s) 3) Used when interface not available
4) All interfaces proxied 4) Cannot be applied to final classes or methods
Spring's Aspect-Oriented Programming (AOP) with annotations to create a proxy, you can utilize the @Aspect annotation along with pointcut expressions to specify where the advice (additional behavior) should be applied. Here's an example:
@LogExecutionTime annotation that can be used to annotate methods you want to log the execution time for.@LogExecutionTime that can be applied to methods.MyService with two methods. One method (doSomething) represents a regular method, and the other metho (annotatedMethod) is annotated with @LogExecutionTime. LoggingAspect class. It is annotated with @Aspect and @Component. We define a pointcut (logExecutionTimeAnnotation) that matches methods annotated with @LogExecutionTime. The @Around advice logs method entry, exit, and execution time.@EnableAspectJAutoProxy annotation enables AspectJ proxy support.In this step, we create a simple controller (
MyController) that uses theMyServiceinterface.
Now, when you run your Spring Boot application and make requests to /doSomething and /annotatedMethod, you'll observe log entries in the console generated by the LoggingAspect. The aspect intercepts the method calls and provides additional behavior based on the presence of the @LogExecutionTime annotation, demonstrating the proxy design pattern in action.






Comments
Post a Comment