Skip to main content
AOP and proxies · Topic 3 of 5

Pointcut expressions

Definition​

A pointcut expression says which methods an advice applies to. You can match by method signature (execution), by package or class (within), or by a custom annotation (@annotation). Annotations are the clearest way to mark exactly what you want.

Example code​

Matching methods by a custom annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Audited { } // our own marker annotation

@Service
class AccountService {
@Audited
void closeAccount(String id) { System.out.println("closing " + id); }

void viewAccount(String id) { System.out.println("viewing " + id); }
}

@Aspect
@Component
class AuditAspect {
@Before("@annotation(Audited)") // only methods carrying @Audited
void audit(JoinPoint call) { System.out.println("AUDIT: " + call.getSignature().getName()); }
}

@ComponentScan
@EnableAspectJAutoProxy
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
AccountService accounts = context.getBean(AccountService.class);
accounts.viewAccount("A1"); // not audited
accounts.closeAccount("A1"); // audited
}
}
}

// Output:
// viewing A1
// AUDIT: closeAccount
// closing A1

Finished this page? Track your progress (saved only in your browser).