Java 控制器中所有方法的 Spring AOP 切入点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23607872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:18:06  来源:igfitidea点击:

Spring AOP pointcut for all methods in a controller

javaspringspring-mvcspring-aoppointcut

提问by Goose

I want to run some code before every method in a Spring (3.2.3) @Controller. I have the following defined but it won't run. I suspect the pointcut expression is incorrect.

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

dispatcher-servlet.xml

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

采纳答案by kriegaex

Your pointcut expression is missing a return type like void, Stringor *, e.g.

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

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

回答by Sean Patrick Floyd

The correct way to do it in current versions of Spring MVC is through a ControllerAdvice.
See: Advising controllers with the @ControllerAdviceannotation

在当前版本的 Spring MVC 中执行此操作的正确方法是通过ControllerAdvice.
请参阅:使用@ControllerAdvice注释为控制器提供建议

For previous versions, refer to this answer of mine: https://stackoverflow.com/a/5866960/342852

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

回答by geoand

Besides @ControllerAdvicethat is already mentioned in another answer, you should check out Spring MVC interceptors.

除此之外@ControllerAdvice,在另一个答案中已经提到过,您应该查看Spring MVC 拦截器

They basically simplify AOP for controllers and can be used in cases where @ControllerAdvicedoesn't give you enough power.

它们基本上简化了控制器的 AOP,可以在@ControllerAdvice没有给你足够能力的情况下使用。