尝试在Aspect中获取请求对象时,我发现了两种解决方案。我想知道在性能方面哪个更好。这是详细信息。
我想对所有用'@myAnnotation'注释的方法执行myAspectMethod。因此,在我使用请求对象执行业务逻辑的地方,只要春天在方法级别找到@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 {
}
在上述两种不同的请求对象使用方式之间,从性能角度来看哪种更好?这是我想知道答案的重要问题。
每种方法的其他优点和缺点是什么。
我不确定第一种方法是否有效。即使您可以通过HttpServletRequest
这种方式自动布线,也必须将方面设为请求范围。
我认为最好的选择是使用RequestContextHolder
:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
该方法使用Spring已经填充的线程本地存储,不需要在方法签名中进行任何更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句