Loading

Quipoin Menu

Learn • Practice • Grow

spring / Example Project for AOP
tutorial

Example Project for AOP

Theory is good, but let us build a real project to see AOP in action. We will create a simple banking application where we want to:
  • Log every transaction for auditing.
  • Measure performance of slow methods.
  • Check user permissions before withdrawing money.
All without modifying the original service code.

Step 1: Create the Service Class


@Service
public class BankService {

public void deposit(String account, double amount) {
System.out.println("Depositing " + amount + " to " + account);
}

public void withdraw(String account, double amount) {
System.out.println("Withdrawing " + amount + " from " + account);
}

public double checkBalance(String account) {
// Simulate slow database call
try { Thread.sleep(2000); } catch (InterruptedException e) {}
return 5000.0;
}
}

Step 2: Create Logging Aspect


@Aspect
@Component
public class LoggingAspect {

@Before("execution(* com.example.service.BankService.*(..))")
public void logTransaction(JoinPoint jp) {
System.out.println("Transaction: " + jp.getSignature().getName()
+ " called with args: " + Arrays.toString(jp.getArgs()));
}
}

Step 3: Create Performance Aspect


@Aspect
@Component
public class PerformanceAspect {

@Around("execution(* com.example.service.BankService.checkBalance(..))")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed();
long end = System.currentTimeMillis();
System.out.println("Method " + pjp.getSignature().getName()
+ " took " + (end - start) + " ms");
return result;
}
}

Step 4: Enable AOP in Configuration


@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {
}

Now when you run your application, AOP automatically adds logging before every transaction and measures time for balance checks without touching the BankService code.
Two Minute Drill
  • AOP lets you add cross-cutting concerns without modifying original code.
  • Use @Before for logging, @Around for performance monitoring.
  • Enable AOP with @EnableAspectJAutoProxy.
  • Pointcut expressions target specific methods.
  • This keeps your business code clean and focused.

Need more clarification?

Drop us an email at career@quipoinfotech.com