【发布时间】:2019-11-13 14:12:59
【问题描述】:
在尝试在 Aspect 中获取请求对象时,我找到了两个解决方案。我想知道性能方面哪个更好。以下是详细信息。
我想为所有由“@myAnnotation”注释的方法执行 myAspectMethod。因此,只要 spring 在方法级别找到 @myAnnotation,myAspectMethod 就会在我使用请求对象执行业务逻辑的地方执行。为了得到请求,我找到了两个解决方案
-
在 Aspect 类中注入请求对象,例如
下面@Aspect public class MyAspect { @Autowired(required = true) **private HttpServletRequest request;** @Around("@annotation(myAnnotation)") public Object myAspectMethod(ProceedingJoinPoint pjp, MyAnnotation myAnnotation) throws Throwable { //....do something with request object } } 通过在带注释的方法中将请求对象作为参数发送并通过收到的参数列表访问它
Aspect 中的访问请求
@RequestMapping(method = { RequestMethod.GET }, value = "/something")
@MyAnnotation
public Object myAnnotatedMethod(**HttpServletRequest request**)
{
//....some business logic
}
@Aspect
public class MyAspect {
@Around("@annotation(myAnnotation)")
public Object myAspectMethod(ProceedingJoinPoint pjp,
MyAnnotation myAnnotation) throws Throwable {
HttpServletRequest request = getRequestArgument(pjp);
....do something with request object
}
private HttpServletRequest getRequestArgument(ProceedingJoinPoint pjp) {
for (Object object : pjp.getArgs()) {
if (object instanceof HttpServletRequest) {
return (HttpServletRequest) object;
}
}
return null;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
}
在以上两种不同的请求对象使用方式之间,从性能角度来看,哪一种更好?这是一个重要的问题,我想知道答案。
每种方法的其他优缺点是什么。
【问题讨论】:
标签: java spring performance aop