Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 119 ยท Spring Framework

Spring AOP: XML Configuration and the Classic Advice API

Read and migrate older Spring AOP code - aop:config with aop:aspect, ProxyFactoryBean, MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice and MethodInterceptor.

The AOP lesson used @Aspect classes and annotations, which is how almost all new Spring code is written. But Spring AOP is older than annotations. Before Java 5 there were no annotations at all, so aspects were declared in XML, and before that Spring had its own classic advice API built around ProxyFactoryBean. Plenty of production systems, banks and insurance back offices in particular, still run on those styles. If you ever open a applicationContext.xml full of <aop:config> blocks, or a class that implements MethodInterceptor, this lesson tells you what you are looking at and how to move it to the modern style.

None of this needs a different idea. XML and the classic API describe the same four things as annotations: which methods (a pointcut), what to run (advice), in which bean (an aspect or advisor), and how it is applied (a proxy). If you are not yet comfortable with those words, read Aspect-Oriented Programming first, and Spring XML Configuration if the XML below looks unfamiliar.

Spring cannot run in this page's editor. The Spring XML and classic API code is shown read-only and is the real thing. The runnable examples are stand-ins written in plain Java: they copy the shape of Spring's interfaces and the behavior of the proxy chain, so you can watch the mechanics, but they are not Spring.

XML aspects with aop:config

In the XML style, an aspect is an ordinary class with no annotations and no Spring or AspectJ imports (except ProceedingJoinPoint for around advice). The XML says which method is which kind of advice:

Java
package com.example.bank.audit;

public class AuditAspect {

    public void logCall(JoinPoint call) {                       // before
        System.out.println("-> " + call.getSignature().getName());
    }

    public void logResult(JoinPoint call, Object result) {      // after-returning
        System.out.println("<- " + call.getSignature().getName() + " = " + result);
    }

    public void logFailure(JoinPoint call, Exception ex) {      // after-throwing
        System.out.println("!! " + call.getSignature().getName() + ": " + ex.getMessage());
    }

    public Object time(ProceedingJoinPoint call) throws Throwable {   // around
        long start = System.nanoTime();
        try {
            return call.proceed();
        } finally {
            System.out.println(call.getSignature().getName() + " took "
                + (System.nanoTime() - start) / 1_000 + " ยตs");
        }
    }
}
XML
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/aop   https://www.springframework.org/schema/aop/spring-aop.xsd">

  <bean id="accountService" class="com.example.bank.service.DefaultAccountService"/>
  <bean id="auditAspect"    class="com.example.bank.audit.AuditAspect"/>

  <aop:config>
    <aop:pointcut id="accountOps"
                  expression="execution(* com.example.bank.service.AccountService.*(..))"/>

    <aop:aspect id="auditing" ref="auditAspect" order="10">
      <aop:before          pointcut-ref="accountOps" method="logCall"/>
      <aop:after-returning pointcut-ref="accountOps" method="logResult" returning="result"/>
      <aop:after-throwing  pointcut-ref="accountOps" method="logFailure" throwing="ex"/>
      <aop:around          pointcut-ref="accountOps" method="time"/>
    </aop:aspect>
  </aop:config>
</beans>

Reading it from the top:

  • <aop:pointcut> names a pointcut with the same AspectJ expression language as @Pointcut. The id is how the advice elements refer to it (pointcut-ref). You can also write the expression inline with pointcut="...".
  • <aop:aspect ref="auditAspect"> says "the methods of this bean are advice". The optional order plays the role of @Order: lower numbers are the outer layer.
  • Each advice element maps to an annotation you already know: aop:before is @Before, aop:after-returning is @AfterReturning (with returning naming the parameter that receives the result), aop:after-throwing is @AfterThrowing, aop:after is @After and aop:around is @Around.
  • Argument binding works by parameter name or type: a JoinPoint first parameter is passed automatically, and returning/throwing name the parameters that receive the result or exception. The arg-names attribute helps when classes are compiled without parameter names.

You can add <aop:advisor> to attach a classic Advice bean (next section) with a pointcut, in the same <aop:config>. And <aop:config proxy-target-class="true"> forces CGLIB proxies, like spring.aop.proxy-target-class does in Boot.

aop:config versus aspectj-autoproxy

There are two XML switches, and mixing them up is a classic confusion:

Element What it does
<aop:config> Declares aspects in XML. The aspect classes need no annotations.
<aop:aspectj-autoproxy/> Turns on processing of @Aspect annotated beans (this is what @EnableAspectJAutoProxy does in Java config).

Use one style per aspect. An @Aspect class registered as a bean but never enabled with <aop:aspectj-autoproxy/> simply does nothing, with no error: another case of "my aspect is ignored".

The classic advice API

The oldest style has no pointcut language at all. You write advice as a class implementing one of a few interfaces from org.springframework.aop and org.aopalliance.intercept:

Interface Runs Can change the call?
MethodBeforeAdvice before the target method: before(Method, Object[] args, Object target) No, but it can throw to block the call
AfterReturningAdvice after normal return: afterReturning(Object result, Method, Object[], Object target) No (cannot replace the result)
ThrowsAdvice after the target throws; a marker interface, Spring finds methods named afterThrowing(...) by reflection No
MethodInterceptor around the call: invoke(MethodInvocation), with invocation.proceed() Yes: change arguments, result, skip the call

MethodInterceptor is the most powerful and the only one of the four that can swallow an exception or return a different value; the first three are conveniences. @Around is its modern descendant.

Wiring uses a ProxyFactoryBean. You name the target, the advice (or advisors) and the interfaces to proxy, and the factory bean produces the proxy:

Java
public class AuditBeforeAdvice implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) {
        System.out.println("-> " + method.getName() + Arrays.toString(args));
    }
}

public class TimingInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        long start = System.nanoTime();
        try {
            return invocation.proceed();               // go to the next advice, then the target
        } finally {
            System.out.println(invocation.getMethod().getName() + " took "
                + (System.nanoTime() - start) / 1_000 + " ยตs");
        }
    }
}
XML
<bean id="accountServiceTarget" class="com.example.bank.service.DefaultAccountService"/>

<bean id="auditBefore"  class="com.example.bank.audit.AuditBeforeAdvice"/>
<bean id="timing"       class="com.example.bank.audit.TimingInterceptor"/>

<!-- An advisor = a pointcut + advice. This one matches methods by name. -->
<bean id="withdrawAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
  <property name="mappedNames" value="withdraw,transfer*"/>
  <property name="advice"      ref="auditBefore"/>
</bean>

<!-- The proxy that other beans actually inject, under the id "accountService". -->
<bean id="accountService" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="target"          ref="accountServiceTarget"/>
  <property name="proxyInterfaces" value="com.example.bank.service.AccountService"/>
  <property name="interceptorNames">
    <list>
      <value>timing</value>           <!-- advice or advisor bean names, outermost first -->
      <value>withdrawAdvisor</value>
    </list>
  </property>
</bean>

Things that surprise people the first time:

  • A bare Advice bean in interceptorNames applies to every method. To restrict it, wrap it in an advisor (NameMatchMethodPointcutAdvisor, RegexpMethodPointcutAdvisor, or DefaultPointcutAdvisor with your own Pointcut).
  • Other beans must inject the proxy, so the target gets an inner name or a different id (accountServiceTarget), and the ProxyFactoryBean gets the "real" id. Inject the target by mistake and nothing is advised.
  • One ProxyFactoryBean per bean gets verbose very quickly. Classic Spring answered that with auto-proxy creators: BeanNameAutoProxyCreator (apply these interceptors to every bean whose name matches *Service) and DefaultAdvisorAutoProxyCreator (apply every advisor in the context to every bean it matches). Both are still the engine under today's annotation support.
  • The proxy rules are the ones from the AOP lesson: JDK proxy for interfaces, CGLIB otherwise, and no advice on self-invocation.

Seeing the mechanics: a classic-style chain in plain Java

Spring's own classes can't load here, so the next example re-creates the classic design in about 80 lines: the four advice types with Spring's method shapes, adapters that turn each into a MethodInterceptor, a name-matching advisor, and a proxy that runs the chain with a MethodInvocation that remembers its position. This is how ProxyFactoryBean works internally (Spring wraps before/after/throws advice in interceptor adapters, then runs a chain of interceptors); the stand-in only shrinks the class names and drops CGLIB.

Java A classic advice chain (stand-in for ProxyFactoryBean)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that result printed nothing for the failed call (an after-returning advice only runs on a normal return), that failure rethrew so the caller still got the exception, and that the order in which advice is added decides who is outermost. With Spring's interceptorNames the rule is the same: the first name is the outermost layer.

XML aspects, simulated

The second example is a tiny interpreter for the <aop:aspect> block. It reads real XML with the JDK's DOM parser, finds the aspect bean, and for each aop:before, aop:after-returning, aop:after-throwing and aop:around element calls the named method by reflection, which is exactly the job of Spring's AspectJAfterAdvice and friends. The pointcut language is cut down to execution(* Type.method(..)) with * wildcards in the method name. Real AspectJ expressions match return types, packages, annotations and parameters.

Java Interpreting aop:aspect XML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The shape matches the XML you saw earlier: the aspect has no idea it is an aspect, the XML wires methods to kinds of advice, and the around advice is the outer layer. The stand-in runs before before around, whereas real Spring orders advice of one aspect by kind and declaration (around advice first, then before, and so on) and lets order break ties between aspects, so never depend on fine ordering details without testing.

Moving to annotations

Migration is mechanical, and you can do it one aspect at a time because both styles can live in the same context:

Old New
<aop:aspect ref="auditAspect"> plus advice elements @Aspect on the class (and @Component), annotation on each advice method
<aop:pointcut id="x" expression="..."> @Pointcut("...") void x() {}
<aop:before method="m" pointcut-ref="x"> @Before("x()") on m
<aop:around> @Around("x()") with a ProceedingJoinPoint parameter
MethodInterceptor + NameMatchMethodPointcutAdvisor + ProxyFactoryBean one @Around aspect and a pointcut such as execution(* ..AccountService.withdraw(..))
BeanNameAutoProxyCreator a pointcut with bean(*Service) or within(...)
<aop:config proxy-target-class="true"> @EnableAspectJAutoProxy(proxyTargetClass = true) (automatic in Spring Boot)
<aop:aspectj-autoproxy/> @EnableAspectJAutoProxy

Two things to check after migrating: the order of aspects (add @Order where the XML had order), and which beans are proxied (a name-matching auto-proxy creator may have advised beans that your new pointcut no longer matches, or vice versa). A test that calls the bean and asserts the audit line or the timing is cheap insurance.

If you are only maintaining the code, you do not have to migrate. The classic API and the XML elements are still supported, and Spring has not announced plans to remove them. But write anything new with @Aspect, because that is what the rest of the ecosystem, the documentation and your colleagues expect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In an aop:aspect block, which XML element corresponds to the @Around annotation?

    Each advice element has an annotation twin. aop:around names a method taking a ProceedingJoinPoint, like an @Around method. aop:pointcut only declares a reusable pointcut.
  2. 2. You register an @Aspect class as a bean in an XML context but never add aop:aspectj-autoproxy (or @EnableAspectJAutoProxy). What happens?

    The annotations are only read by the auto-proxy infrastructure. Without it the class is just a bean, and no error is reported.
  3. 3. A ProxyFactoryBean is configured with id "accountService" and the target bean has id "accountServiceTarget". Another bean is injected with the target by mistake. What is the effect?

    Advice lives in the proxy. A bean that holds a direct reference to the target bypasses it, just like self-invocation does.
  4. 4. Which classic advice type can replace the return value or skip the target method?

    Only MethodInterceptor controls proceed(). The other three observe the call and can at most throw an exception.
  5. 5. An old interceptorNames list is "timing, withdrawAdvisor". Which one wraps the other?

    The first interceptor name is the outermost layer of the chain, so timing measures the advisor's work as well as the target.

Summary

  • Spring AOP has three configuration styles: @Aspect annotations (modern), XML aop:config (aspects as plain classes wired in XML) and the classic API (ProxyFactoryBean, advisors, advice interfaces). All of them end in the same thing: a proxy running a chain of interceptors.
  • In XML, aop:pointcut names an AspectJ expression, aop:aspect ref points to the aspect bean, and aop:before, aop:after-returning, aop:after-throwing, aop:after and aop:around map to the matching annotations.
  • Classic advice comes in four types: MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice and the all-powerful MethodInterceptor. A bare advice bean applies to every method; use an advisor with a pointcut to narrow it.
  • Inject the proxy, not the target, and remember that self-invocation, private and final methods are not advised in any style.
  • aop:config declares XML aspects; aop:aspectj-autoproxy enables @Aspect classes. Migrate one aspect at a time, keep the order, and test which beans are advised.

Next: Spring JDBC with JdbcTemplate and JdbcClient.