Sub topic 9
Selecting Join Points with Pointcut Expressions
A pointcut expression tells Spring which method executions an aspect should wrap. This chapter assumes you know core Java annotations, basic Spring bean configuration, and the AOP vocabulary from earlier chapters: aspect, join point, advice and pointcut. It also assumes you know that Spring AOP works through proxies. In Spring AOP, a join point is always a method execution on a Spring bean.
How Spring reads a pointcut
Spring uses a subset of the AspectJ pointcut language. It parses the expression when the application context starts. For each bean, it checks every method against the expression. If at least one method matches, Spring wraps the bean in a proxy.
Because only method executions on proxied beans are join points, many AspectJ designators do not work. Field access, constructor calls and static initializers are unsupported. Using an unsupported designator fails at startup with an IllegalArgumentException.
The table lists the designators you will use most.
| Designator | Matches | Example |
|---|---|---|
| `execution` | Method signature | `execution(* com.example.service..*(..))` |
| `within` | All methods of types in a package or type | `within(com.example.service..*)` |
| `this` | Proxy is an instance of a type | `this(com.example.Auditable)` |
| `target` | Target object is an instance of a type | `target(com.example.Repository)` |
| `args` | Runtime argument types | `args(String, ..)` |
| `@annotation` | Method carries an annotation | `@annotation(com.example.Audited)` |
| `@within` | Declaring class carries an annotation | `@within(org.springframework.stereotype.Service)` |
| `@target` | Target object's class carries an annotation | `@target(com.example.Secured)` |
| `@args` | Argument types carry an annotation | `@args(com.example.Sensitive)` |
| `bean` | Spring bean name (Spring-specific) | `bean(*Service)` |
The execution designator
execution is the designator you will write most often. Its full form is:
execution(modifiers? return-type declaring-type? method-name(params) throws?)Only the return type, method name and parameters are required. Here is what each part allows:
*matches any single element, such as one return type, one name segment or one parameter...in a package position means "this package and all subpackages"...in a parameter list means "zero or more parameters of any type".+after a type name means that type and its subtypes.
Some examples:
execution(public * *(..))
execution(* save*(..))
execution(* com.example.service.OrderService.*(..))
execution(* com.example.service.*.*(..))
execution(* com.example.service..*.*(..))
execution(String com.example..*Service.find*(Long))
execution(* com.example.Repository+.*(..))The first matches any public method. The second matches methods whose names start with save. The third matches every method of one class. The fourth matches the service package only. The fifth also matches its subpackages. The sixth matches find* methods that take a single Long and return String. The last matches every method on Repository and its implementations.
The declaring-type part is a common source of confusion. .*(..) after a package means "any type in that package". ..* means "any type in this package or its subpackages".
Combining and naming pointcuts
Pointcuts combine with &&, || and !. You can name a pointcut by declaring it on an empty method with @Pointcut. You can then reuse the name in several advice annotations.
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceLoggingAspect {
@Pointcut("within(com.example.service..*)")
void inServiceLayer() {}
@Pointcut("execution(* *..find*(..))")
void finders() {}
@Pointcut("inServiceLayer() && finders()")
void serviceFinders() {}
@Pointcut("serviceFinders() && !execution(* *..findInternal*(..))")
void publicServiceFinders() {}
@Before("publicServiceFinders()")
public void log(JoinPoint jp) {
System.out.println("calling " + jp.getSignature().toShortString());
}
}Visibility rules apply to named pointcuts. A public pointcut can be referenced from other aspects as ServiceLoggingAspect.serviceFinders(). A private one is usable only inside its own aspect. Many teams keep shared pointcuts in one central class, for example SystemArchitecture, so the architecture rules live in one place.
Binding arguments and the proxy
A pointcut can capture values from the join point and pass them to the advice. Name the parameter in the expression, and declare a parameter with the same name in the advice method.
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ArgumentAspect {
@Before("execution(* com.example.service.*.*(..)) && args(id, ..)")
public void checkId(Long id) {
if (id != null && id < 0) {
throw new IllegalArgumentException("negative id: " + id);
}
}
}This advice runs only for methods in that package whose first argument is a Long. The value arrives already typed. The this, target and @annotation designators bind in the same way.
this and target differ in what they test:
thistests the proxy object.targettests the object behind the proxy.
With a JDK proxy, the proxy implements only the interfaces. this(com.example.OrderServiceImpl) therefore will not match, while target(com.example.OrderServiceImpl) will. With a CGLIB proxy, both match.
Choosing between execution, within and annotations
Use this decision order:
- Use
@annotation(...)when developers should opt in explicitly. This is the most readable choice for cross-cutting behavior like auditing. - Use
within(...)for architectural rules such as "everything in the service layer". It is cheaper to evaluate thanexecution. - Use
execution(...)when you need to filter by method name, return type or parameters. - Use
bean(...)for a quick match by bean name. It is not portable to AspectJ weaving.
Common errors
- A pattern is too broad.
execution(* *(..))matches every method on every bean, including framework beans, and can cause surprising proxying or startup failures. Always restrict by package. - The pointcut matches, but advice never runs. The call may bypass the proxy. The next chapters cover self-invocation and the limits of final and private methods.
- The expression is mistyped. Spring reports a malformed expression at startup. A well-formed expression with a wrong package name matches nothing and fails silently. Verify with a log line or a test.
- A parameter name does not match. When an
argsor@annotationbinding name differs from the advice method parameter, startup fails with an error such as "formal unbound in pointcut".
Exercise
You want advice to run only for methods annotated with @Audited that are declared in classes inside com.example.service or its subpackages, and you want the annotation bound to the advice parameter audited. Write the pointcut expression.
Show answer
@annotation(audited) && within(com.example.service..*). The advice method must declare a parameter named audited of the annotation type. within limits matching to the service package tree, and @annotation binds the annotation instance.
Exercise
A bean is proxied with a JDK dynamic proxy and implements OrderService. The concrete class is OrderServiceImpl. Does this(com.example.OrderServiceImpl) match its methods? Does target(com.example.OrderServiceImpl)?
Show answer
this does not match, because the JDK proxy implements only the interface and is not an OrderServiceImpl. target matches, because it tests the object behind the proxy, which is an OrderServiceImpl.