implement AOP for Controllers in Spring 3
- by tommy
How do I implement AOP with an annotated Controller?
I've search and found two previous posts regarding the problem, but can't seem to get the solutions to work.
posted solution 1
posted solution 2
Here's what I have:
Dispatch Servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.foo.controller"/>
<bean id="fooAspect" class="com.foo.aop.FooAspect" />
<aop:aspectj-autoproxy>
<aop:include name="fooAspect" />
</aop:aspectj-autoproxy>
</beans>
Controller:
@Controller
public class FooController {
@RequestMapping(value="/index.htm", method=RequestMethod.GET)
public String showIndex(Model model){
return "index";
}
}
Aspect:
@Aspect
public class FooAspect {
@Pointcut("@target(org.springframework.stereotype.Controller)")
public void controllerPointcutter() {}
@Pointcut("execution(* *(..))")
public void methodPointcutter() {}
@Before("controllerPointcutter()")
public void beforeMethodInController(JoinPoint jp){
System.out.println("### before controller call...");
}
@AfterReturning("controllerPointcutter() && methodPointcutter() ")
public void afterMethodInController(JoinPoin jp) {
System.out.println("### after returning...");
}
@Before("methodPointcutter()")
public void beforeAnyMethod(JoinPoint jp){
System.out.println("### before any call...");
}
}
The beforeAnyMethod() works for methods NOT in a controller; I cannot get anything to execute on calls to controllers. Am I missing something?