2014-05-12 91 views
6

我想在Spring(3.2.3)@Controller的每個方法之前運行一些代碼。我有以下定義,但它不會運行。我懷疑切入點表達式是不正確的。控制器中所有方法的Spring AOP切入點

調度-servlet.xml中

<aop:aspectj-autoproxy/> 
<bean class="com.example.web.controllers.ThingAspect"/> 

c.e.w.c.ThingAspect

@Pointcut("execution(com.example.web.controllers.ThingController.*(..))") 
public void thing() { 
} 

@Before("thing()") 
public void doStuffBeforeThing(JoinPoint joinPoint) { 
    // do stuff here 
} 
+1

也許['@ ControllerAdvice'](http://docs.spring.io/spring/docs/4.0.3.RELEASE/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice .html)是你正在尋找的。 –

+0

它是(a)完全不運行還是(b)某些方法沒有運行?這將有助於診斷您的問題。 – Phil

+0

我不知道ControllerAdvice是否存在,但是查看了將ExceptionHandler,InitBinder和ModelAttribute附加到多個控制器的文檔。我正在尋找一些東西來運行每個方法,在我的情況下都是RequestMapping註釋方法。目前該方面根本沒有被任何方法調用。我可以使用Spring Interceptor,但AOP看起來非常適合這項任務。 – Goose

回答

4

您的切入點表達式缺少返回類型,例如voidString*,例如,

execution(* com.example.web.controllers.ThingController.*(..)) 
7

做Spring MVC中的當前版本的正確方式是通過一個ControllerAdvice
請參閱:Advising controllers with the @ControllerAdvice annotation

對於先前的版本,請參考這個答案我的: https://stackoverflow.com/a/5866960/342852

+0

這應該被標記爲接受的答案...... – kaqqao

+0

@kaqqao我不同意,'@ ControllerAdvice'只有一組特定的可能性。你可以使用@ ModelAttribute來攔截每個'@ RequestMapping'方法,但是你只有'Model'的上下文,沒有別的。我認爲你應該upvote @geoand,雖然我沒有看過Spring MVC攔截器,但我認爲'ControllerAdvice'功能不夠強大。 – froginvasion

+0

@geoand答案確實很好,我剛剛提高了評價。儘管如此,這個問題並沒有詳細說明具體細節,只是在每個方法和'@ ControllerAdvice'之前應該運行一些東西...... – kaqqao

2

除此之外在另一個答案已經提到@ControllerAdvice,你應該看看Spring MVC interceptors

它們基本上簡化了控制器的AOP,並且可以在@ControllerAdvice不能給你足夠的功率的情況下使用。