DEV Community

eidher
eidher

Posted on • Updated on

Spring AOP

Aspect-Oriented Programming (AOP) enables the modularization of generic functionalities that are needed in many places (join points) like logging, security, caching, error handling, etc.

Spring AOP uses dynamic proxies (enhanced classes that stand in place of the originals) for aspect weaving (combining aspects with the code). An aspect is a java class that contains pointcuts (expressions that select one or more join points) and advice (code to be executed at each selected join point).

For example, let's implement an aspect for logging. First, we need to enable the use of the @Aspect annotation by adding the @EnableAspectJAutoProxy annotation in the @Configuration (see Spring Configuration) class (with its respective @ComponentScan to the packages with the aspects). Now we can create the @Aspect:

@Aspect
@Component
public class LoggingAspect {

    private Logger logger = Logger.getLogger(getClass());

    @Before("execution(public * package_name.*(..))")
    public void log() {
          logger.info("Logging from aspect");
    }
}
Enter fullscreen mode Exit fullscreen mode

We can receive the JoinPoint (or its subinterface ProceedingJoinPoint) as a parameter in the methods and to get some properties (see JoinPoint interface). And not only to use the @Before annotation over the methods, but to use other annotations from the org.aspectj.lang.annotation package as @Around, @After, @AfterReturning, and @AfterThrowing, followed by the context about the intercepted point using AspectJ's pointcut expression language (wildcard asterisk matches once, two points match zero or more) for selecting where to apply the advice (see AspectJ Documentation).

Take into account:

  • If a @Before advice throws an exception, the target will not be called.
  • You can only advise non-private methods.
  • You can only apply aspects to Spring Beans.

Oldest comments (0)