Tuesday, 10 June 2025

AOP in java

 AOP (Aspect-Oriented Programming) is a programming paradigm that allows you to separate cross-cutting concerns (like logging, security, transactions) from your business logic, especially useful in Spring Framework.

What is a Cross-Cutting Concern?

A concern that affects multiple parts of your application:

  • Logging

  • Security

  • Transaction Management

  • Exception Handling

  • Caching

๐ŸŽฏ Why AOP?

Instead of writing the same logging or security code in every method, AOP lets you define that logic once and apply it transparently across the application.

✅ AOP Terminology

TermMeaning
AspectA class that contains cross-cutting logic
Join PointA point during execution (e.g., method call) where an aspect can be applied
AdviceAction taken by an aspect (before, after, around method execution)
PointcutExpression that matches join points (e.g., all @Service methods)
WeavingLinking aspects with other application types at runtime or compile time

๐Ÿ“ 1. Maven Dependency (Optional)

If you're using Spring Boot Starter, AOP support is already included. If not:

<!-- Add this in pom.xml if not using spring-boot-starter -->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>

๐Ÿงฑ 2. Enable AOP in Main Class

@SpringBootApplication
@EnableAspectJAutoProxy public class AopDemoApplication { public static void main(String[] args) { SpringApplication.run(AopDemoApplication.class, args); } }

๐Ÿงฉ 3. Create a Service Class (Business Logic)

@Service
public class MyService { public String greet(String name) { System.out.println("Inside greet()"); return "Hello, " + name; } }

๐ŸŽฏ 4. Create an Aspect Class

@Aspect
@Component public class LoggingAspect { @Before("execution(* com.example.demo.service.*.*(..))") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("Before Method: " + joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "execution(* com.example.demo.service.*.*(..))", returning = "result") public void afterReturningAdvice(JoinPoint joinPoint, Object result) { System.out.println("After Returning: " + joinPoint.getSignature().getName() + ", result: " + result); } @AfterThrowing(pointcut = "execution(* com.example.demo.service.*.*(..))", throwing = "ex") public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) { System.out.println("Exception in " + joinPoint.getSignature().getName() + ": " + ex); } @Around("execution(* com.example.demo.service.*.*(..))") public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Before Around: " + pjp.getSignature().getName()); Object result = pjp.proceed(); // proceed with method execution System.out.println("After Around: " + pjp.getSignature().getName()); return result; } }

๐Ÿงช 5. Calling the Service

@RestController
@RequestMapping("/api") public class MyController { @Autowired private MyService myService; @GetMapping("/greet") public String greet(@RequestParam String name) { return myService.greet(name); } }

✅ Output on Request /api/greet?name=John

Before Around: greet
Before Method: greet Inside greet() After Returning: greet, result: Hello, John After Around: greet

๐Ÿ“Œ Summary

FeatureDescription
@AspectDeclares a class as an Aspect
@BeforeRuns before matched method
@AfterReturningRuns after successful execution
@AfterThrowingRuns after method throws an exception
@AroundWraps method, giving full control (most powerful)
PointcutPattern to match method execution


No comments:

Post a Comment