Nep*_*s76 9 spring-mvc spring-aop spring-4 spring-restcontroller
我创建了一个Aspect,它执行基本的id比较,以确保用户属于创建所请求实体的同一组.我已成功将我的方面附加到@Service方法,但它在服务层上没有意义,我需要将它附加到@RestController方法.当我尝试这样做时,一切似乎都很好,但我的Aspect从未触发,日志也是静默的.
的pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
春天的背景
<context:annotation-config/>
<context:component-scan base-package="my.pkg"/>
<aop:aspectj-autoproxy/>
<aop:config proxy-target-class="true"/>
Run Code Online (Sandbox Code Playgroud)
方面
@Aspect
@Component
public class MyAspect {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {}
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restController() {}
@Pointcut("args(java.security.Principal,..)")
public void principalArgPointcut() {}
@Around("(controller() || restController()) && principalArgPointcut()")
public Object validate(ProceedingJoinPoint point) throws Throwable {
doValidationBefore();
Object result = point.proceed();
doValidationAfter();
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
其中"doValidationBefore()"和"doValidationAfter()"将在验证失败时抛出异常.
最后,我的RestController
@RestController
@RequestMapping("/my-path")
public class MyController {
@RequestMapping(value = "/{entityId}", method = RequestMethod.GET)
public @ResponseBody
ResponseEntity<MyEntity> getEntityDetails(Principal principal, @PathVariable("entityId") Long entityId) {
return new ResponseEntity(HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
有些事情需要注意:
我尝试过的事情:
我想在这里得到一些帮助,因为我一直试图解决这个问题很长一段时间.我知道这一定是可能的.
事实证明,我的Aspect和我的控制器实际上并不是在同一个环境中.
虽然我认为我的控制器包含在我的web-context.xml的上下文扫描中,但它们实际上是在WEB-INF/servlet-context.xml中扫描的.
一旦我将Aspect配置移动到WEB-INF/servlet-context.xml,我的Aspect开始按预期触发.
感谢所有想到我的问题的人.
| 归档时间: |
|
| 查看次数: |
6340 次 |
| 最近记录: |