Sub topic 1
Why Cross-Cutting Concerns Need Their Own Home
Prerequisites
Assume you know Java interfaces, inheritance, annotations, reflection, and basic Spring dependency injection.
Why Cross-Cutting Concerns Need Their Own Home
A cross-cutting concern is behavior needed across many unrelated business operations. Logging, timing, security checks, auditing, and transactions are common examples.
Copying this behavior into every method causes duplication. It also makes business code harder to read and easier to change incorrectly. Aspect-oriented programming (AOP) moves this repeated behavior into a separate component called an aspect.
AOP Vocabulary in Spring Terms
- An aspect is a class containing cross-cutting behavior.
- A join point is an execution point where that behavior could run. Spring AOP mainly uses method executions.
- A pointcut selects matching join points, such as every method in a package.
- Advice is the action that runs at a selected join point.
- Weaving connects advice to the selected code. Spring usually performs this by creating proxies.
The Proxy Pattern: A Stand-In That Adds Behavior
A proxy is an object that has the same usable interface as another object. It receives a call, performs extra work, and delegates to the target.
import java.lang.reflect.Proxy;
interface GreetingService {
String greet(String name);
}
public class ProxyDemo {
public static void main(String[] args) {
GreetingService target = name -> "Hello, " + name;
GreetingService proxy = (GreetingService) Proxy.newProxyInstance(
GreetingService.class.getClassLoader(),
new Class<?>[] { GreetingService.class },
(object, method, arguments) -> {
System.out.println("before");
return method.invoke(target, arguments);
});
System.out.println(proxy.greet("Ada"));
}
}JDK Dynamic Proxies
A JDK dynamic proxy implements one or more interfaces at runtime. Spring can use this option when a bean exposes an interface. Calls made through that interface reach the proxy first.
CGLIB Proxies and Subclassing
A CGLIB proxy is a generated subclass of the target class. Spring uses subclass-based proxying when appropriate, especially when the bean does not expose an interface. Final classes and final methods cannot be overridden, so they cannot be advised this way.
| Proxy type | Main requirement | Limitation |
|---|---|---|
| JDK dynamic proxy | An interface | Calls through the concrete class type are unavailable |
Spring AOP Versus AspectJ
Spring AOP is proxy-based and focuses on methods called through Spring-managed beans. AspectJ uses weaving and can intercept a wider range of join points, including self-invocation, constructors, fields, and objects not created by Spring. Prefer Spring AOP for ordinary service concerns. Consider AspectJ when proxy limitations prevent the required interception.
Exercise
Which proxy style can Spring use for a bean that implements an interface?
Show answer
A JDK dynamic proxy. Spring can also use subclass-based proxying when configured or required.