Apply an aspect to all methods of a Spring MVC controller.

There are sometimes that we need to apply a generic aspect to all methods of a controller.

How do we do that?

Let’s assume that we have aspect A which does something generic like measuring the execution time of each controller method.

I am too lazy and I don’t want to modify my @Around annotation every time that I add a controller in a different package, nor I want to force all of my controllers to “live” in a specific package or even package hierarchy.

So how do we do it?

We use the following annotation on ours aspect’s method:

@Around(value = "@within(org.springframework.web.bind.annotation.RestController)")

and all Spring MVC controllers annotated with @RestController are automatically advised by our aspect.

Of course the same can be applied for other types of aspects like @Before and for controllers annotated with @Controller.

Happy coding!!!