Spring AOP Advice on Annotated Controllers

It’s possible to have advice on annotated controllers.

I assume you want to advice after execution of all methods in classes annotated with @Controller.

Here’s an example:

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class ControllerAspect {

    @Pointcut("within(@org.springframework.stereotype.Controller *)")
    public void controllerBean() {}

    @Pointcut("execution(* *(..))")
    public void methodPointcut() {}

    @AfterReturning("controllerBean() && methodPointcut() ")
    public void afterMethodInControllerClass() {
        System.out.println("after advice..");
    }
}

If you want to use Spring AOP with AspectJ syntax, you also need a configuration file like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="controllerAspect" class="controller.ControllerAspect" />

    <aop:aspectj-autoproxy>
        <aop:include name="controllerAspect" />
    </aop:aspectj-autoproxy>
</beans>

Note: With Spring AOP, the Spring container will only weave Spring beans. If the @Controller object isn’t a Spring bean, you must use AspectJ weaving.

Leave a Comment