AOP





Simple definition:

AOP is a way which add some behavior to a method before and after execution it. To handle the AOP behavior proxy concept has been used. Each beans which need AOP, wrap by proxy object and any incoming call is common through proxy and proxy object is handling AOP part (Normally when inject AOP beans, actually beans not inject and instead if that proxy is injecting and proxy redirect to actual methods).

Optimize version:

AOP is a way to apply behavior before, after, or around method execution without modifying the method itself. Spring AOP uses proxies to achieve this. Only beans that match AOP pointcuts are wrapped in proxy objects. When we inject such a bean, we are actually injecting the proxy, which intercepts method calls, applies AOP logic, and then calls the actual method on the real bean.


Core Spring AOP Annotations (used in custom aspects)

@Aspect --------------------> Marks a class as an aspect that contains AOP advice methods   

@Pointcut --------------------> Defines a reusable expression to match join points            

@Before ----------------------> Advice that runs before a matched method                      

@After -------------------------> Runs after a method (regardless of exception)                 

@AfterReturning -------------> Runs after a method returns successfully                      

@AfterThrowing --------------> Runs after a method throws an exception                       

@Around ----------------------->Runs before and after the method — full control               

@EnableAspectJAutoProxy--> Enables support for AOP proxies (auto-enabled in Spring Boot) 


Spring Framework Annotations That Internally Use AOP

These annotations use AOP internally — when you use them, Spring creates proxies and intercepts method calls automatically.

01. Transaction Management

@Transactional | Automatically starts and commits/rolls back a transaction around a method. Very commonly used in service or repository layers. |


02. Caching (Spring Cache)

@Cacheable -> Caches the result of a method — next calls return from cache instead of executing 

@CachePut ------------> Updates the cache without skipping the method call                                

@CacheEvict ------------> Removes data from the cache                                                       

All of these annotations work using Spring AOP under the hood — they wrap your method with logic to check/update the cache.


03. Asynchronous Execution

 @Async ---> Runs the method in a separate thread (asynchronously) — uses proxy and AOP behavior 


04. Scheduling

@Scheduled ---> Runs a method periodically on a schedule (doesn’t strictly use AOP, but works similarly)


05. Validation

@Validated ---> Enables method-level bean validation using proxies — works well with JSR-303 annotations like @NotNull or @Min

@Valid ---> Used with @Validated for input validation — not AOP by itself, but works with it when @Validated is present  


06. Security

@PreAuthorize, @PostAuthorize --->  Used with Spring Security — restrict access to methods based on roles or conditions (works via proxy and AOP)

@Secured ---> Similar to @PreAuthorize, for access control   

                                                             

Summary Table

AOP core  -----------> @Aspect, @Before, @Around, @Pointcut, @After 

Transaction ---------> @Transactional                                       

Caching -------------> @Cacheable, @CachePut, @CacheEvict               

Async ---------------> @Async                                               

Security ------------> @PreAuthorize, @Secured                            

Validation ---------> @Validated                                           

Scheduling --------> @Scheduled     



Example: Add log message for each method (Before method call and After method call)                                     

implementation "org.springframework.boot:spring-boot-starter-aop"


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {


//@Pointcut("execution(* com.example.demo.service.*.*(..))") // Target all methods in the service package
//@Pointcut("execution(* com.aop.demo..*(..))") // Pointcut for all methods in your application (adjust base package accordingly)
@Pointcut("execution(* com.aop.demo..*(..))")
public void serviceMethods() {
}

@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("[BEFORE] Executing method: " + methodName);
}

@After("serviceMethods()")
public void logAfter(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("[AFTER] Finished executing method: " + methodName);
}
}




Comments

Popular posts from this blog

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.

01. Steps in SQL Query Execution (MySQL)