Sub topic 1
Why cross-cutting concerns need their own home
Prerequisites
This chapter assumes you know the following:
- Core Java: interfaces, inheritance, and annotations.
- Basic Spring dependency injection: beans,
@Component, and@Configuration. - A basic idea of Java reflection, meaning code that inspects and calls methods at runtime.
You do not need any AOP knowledge. This chapter explains the problem that AOP solves. Later chapters cover the vocabulary and the proxy mechanics.
The problem: code that does not belong to one feature
Business logic answers questions such as "how do we transfer money" or "how do we register a user". Around that logic, applications need behavior that is not part of any one feature:
- Logging method calls and their arguments.
- Timing slow operations.
- Checking that the caller is allowed to do something.
- Opening and committing database transactions.
- Retrying a call that failed for a temporary reason.
- Recording an audit trail.
These are called cross-cutting concerns. A cross-cutting concern is a requirement that applies to many unrelated parts of a program. It "cuts across" the modules that you would otherwise organize by feature.
Object-oriented design handles features well. A PaymentService owns payment rules. An OrderService owns order rules. But "log every service call" belongs to neither of them. It belongs to all of them.
What happens without a separate home
Here is a service that mixes its real work with timing and logging.
import java.util.logging.Logger;
public class TransferService {
private static final Logger LOG = Logger.getLogger(TransferService.class.getName());
public void transfer(String from, String to, long cents) {
long start = System.nanoTime();
LOG.info("transfer started: " + from + " -> " + to);
try {
// the actual business logic is one line
System.out.println("Moving " + cents + " cents from " + from + " to " + to);
} catch (RuntimeException e) {
LOG.warning("transfer failed: " + e.getMessage());
throw e;
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
LOG.info("transfer took " + ms + " ms");
}
}
public static void main(String[] args) {
new TransferService().transfer("alice", "bob", 2500);
}
}The business logic is one line. The rest is timing and logging. Now imagine this pattern repeated in fifty methods across twenty classes. Two problems appear.
Code scattering
The same concern is spread over many classes. If you want to change the log format, or add a metric, you edit every copy. If you miss one, the behavior becomes inconsistent. This is called scattering.
Code tangling
Each method now mixes several concerns: business rules, logging, timing, and error handling. This is called tangling. A reader has to separate the real work from the surrounding code before understanding what the method does. Tests also become harder, because a test for the business rule has to cope with the extra behavior.
Both problems make the code harder to change safely. They also tend to grow worse over time, since each new concern adds another layer to every method.
Ways to separate a concern
Before AOP, developers used several techniques. Each one helps, and each one has limits.
| Technique | How it works | Limit |
|---|---|---|
| Helper or utility method | Move the logging or timing code into a shared method. | Each caller still has to invoke it, so the call sites stay scattered. |
| Inheritance | Put the behavior in a base class and extend it. | Java allows one superclass, so only one concern fits cleanly. Unrelated classes end up sharing a base class they should not have. |
| Template method or callback | A base class or helper wraps your code in a fixed sequence and calls it back. | You must restructure each method to fit the template. |
| Decorator | A wrapper class implements the same interface and adds behavior. | You write one wrapper per interface, and each one repeats the same delegation code. |
The decorator is the closest to what AOP does. A decorator wraps a service and runs extra code before or after delegating. The weak point is repetition. If you have thirty service interfaces, you write thirty decorators, and each forwards every method by hand.
The AOP idea
Aspect-oriented programming (AOP) is a way to define a cross-cutting concern once, in one place, and declare where it applies. The concern lives in a unit called an aspect. The business classes stay free of it.
Instead of editing fifty methods, you write a rule like "apply timing to every public method in the service package." The framework applies it. The business code from the earlier example shrinks back to this:
public class TransferService {
public void transfer(String from, String to, long cents) {
System.out.println("Moving " + cents + " cents from " + from + " to " + to);
}
public static void main(String[] args) {
new TransferService().transfer("alice", "bob", 2500);
}
}The timing and logging move into a single aspect. Later chapters show how to write one. For now, the important point is the division of responsibility:
- The business class says what the feature does.
- The aspect says what must happen around it.
- The framework connects the two.
How Spring makes this work
Spring does not rewrite your classes. It wraps your beans in stand-in objects called proxies. A proxy has the same type as the bean. When another bean calls a method, the call reaches the proxy first. The proxy runs the aspect's code and then passes the call to the real object.
This design has a consequence that shapes the rest of the tutorial. Advice only runs when a call goes through the proxy. Calls that bypass the proxy, such as a method calling another method on this, skip the aspect. The chapters on proxies and self-invocation cover this in detail.
Choosing AOP wisely
AOP fits a concern when it is:
- Needed in many places.
- Independent of the business rules of any one place.
- Describable by a rule, such as a package, a naming pattern, or an annotation.
Good candidates are logging, metrics, security checks, transactions, caching, and retries.
AOP is a poor fit when the behavior is specific to one method or changes the business outcome. Hiding real business rules inside an aspect makes the program hard to follow, because the code that runs is no longer visible where the call is written. Debugging also gets harder, since stack traces now include proxy frames. If a concern applies to one or two methods, a plain method call is usually clearer.
What comes next
The next chapter defines the AOP vocabulary: aspect, join point, pointcut, advice, and weaving. Then the tutorial builds up the proxy mechanism that Spring uses to apply those ideas.
Exercise
A team has 40 service classes. Each one has the same try/catch/finally block that logs entry, exit, and execution time. Name the two problems this causes and say how AOP addresses them.
Show answer
The problems are scattering (the same concern is copied into many classes, so one change means 40 edits) and tangling (each method mixes business logic with logging and timing, which makes it harder to read and test). AOP moves the concern into one aspect and applies it by a rule, so the service classes keep only business logic and the logging code exists in one place.
Exercise
Why is a decorator class not enough to solve cross-cutting concerns across thirty service interfaces?
Show answer
A decorator implements one interface, so you need one wrapper class per interface, and each wrapper repeats the same delegation code for every method. The concern is still duplicated, now across wrappers. AOP defines the behavior once and applies it to many types.
Exercise
Which of these is a good candidate for an aspect: (a) checking a user's permission before every service method, (b) computing the interest rate for a loan, (c) timing all repository calls? Explain briefly.
Show answer
(a) and (c). Both apply to many methods, are independent of the business rules in each method, and can be selected by a rule. (b) is a business rule specific to one feature, so it belongs in the loan code where readers can see it.