Loading

Quipoin Menu

Learn • Practice • Grow

spring / Weaving Example
tutorial

Weaving Example

Imagine you have a sweater and you want to add a pocket. You have three options:
  • Sew it while knitting the sweater (compile-time).
  • Add it after the sweater is made but before you wear it (load-time).
  • Pin it on with a brooch whenever you need it (runtime).
In AOP, this process of linking aspects with your code is called weaving.

Spring AOP uses runtime weaving through proxies. When you create a bean, Spring checks if any aspect applies to it. If yes, Spring creates a proxy object that wraps your original bean. When you call a method, the proxy intercepts it and applies the advice.

Here is how runtime weaving works in Spring:


// Original class
@Service
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}

// Aspect
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.Calculator.add(..))")
public void logAdd() {
System.out.println("Add method called");
}
}

// When you get the bean from context
Calculator calc = context.getBean(Calculator.class);
// Spring actually gives you a proxy object
System.out.println(calc.getClass().getName());
// Output: com.example.service.Calculator$$EnhancerBySpringCGLIB$$...

calc.add(5, 3); // Proxy intercepts, logs, then calls real method
Spring creates either:
  • JDK dynamic proxy – if your class implements an interface.
  • CGLIB proxy – if your class does not implement an interface.
Two Minute Drill
  • Weaving = linking aspects with target objects.
  • Spring AOP uses runtime weaving via proxies.
  • Proxy wraps your bean and intercepts method calls.
  • JDK proxy for interfaces, CGLIB for classes.
  • AspectJ supports compile-time and load-time weaving (more powerful but complex).

Need more clarification?

Drop us an email at career@quipoinfotech.com