【问题标题】:Spring AOP pointcut for all methods in a controller控制器中所有方法的 Spring AOP 切入点
【发布时间】:2014-05-12 11:33:05
【问题描述】:

我想在 Spring (3.2.3) @Controller 中的每个方法之前运行一些代码。我定义了以下内容,但它不会运行。我怀疑切入点表达式不正确。

调度程序-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
}

【问题讨论】:

  • 也许@ControllerAdvice 是您正在寻找的。​​span>
  • 它是 (a) 根本没有运行还是 (b) 某些方法没有运行?这将有助于诊断您的问题。
  • 我不知道 ControllerAdvice 存在,但查看它用于将 ExceptionHandler、InitBinder 和 ModelAttribute 附加到多个控制器的文档。我一直在寻找在每个方法之前运行的东西,在我的例子中,这些方法都是 RequestMapping 注释的方法。目前,根本没有为任何方法调用 Aspect。我可以使用 Spring 拦截器,但 AOP 似乎非常适合这项任务。
  • 我忘记用 (at)Aspect 注释我的方面类。然而,@kriegaex 确实发现了其他一些阻止它工作的东西。感谢您的帮助。
  • 对于使用旧版本 Spring MVC(如 3.1 左右)的人,请参考 this,因为我在尝试在非常旧的代码库中引入表单控制器的分析时遇到了一段时间。

标签: java spring spring-mvc spring-aop pointcut


【解决方案1】:

您的切入点表达式缺少返回类型,例如 voidString*,例如

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

【讨论】:

    【解决方案2】:

    在当前版本的 Spring MVC 中执行此操作的正确方法是通过 ControllerAdvice
    见:Advising controllers with the @ControllerAdvice annotation

    对于以前的版本,请参考我的这个答案: https://stackoverflow.com/a/5866960/342852

    【讨论】:

    • @kaqqao 我不同意,@ControllerAdvice 只有一组特定的可能性。您可以使用@ModelAttribute 拦截每个@RequestMapping 方法,但您只有Model 的上下文,没有别的。我认为你应该支持@geoand,虽然我没有看过 Spring MVC 拦截器,但我认为ControllerAdvice 还不够强大。
    • @geoand 答案确实不错,我刚刚投了赞成票。尽管如此,这个问题并没有真正说明细节,只是应该在每个方法之前运行一些东西,@ControllerAdvice 这样做......
    • 他们都做不同的事情。拦截器用于横切关注点,@ControllerAdvice 用于提供模型丰富器和异常处理程序
    【解决方案3】:

    除了在另一个答案中已经提到的@ControllerAdvice,您应该查看Spring MVC interceptors

    它们基本上简化了控制器的 AOP,并且可以在 @ControllerAdvice 无法提供足够功能的情况下使用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多