gpt4 book ai didi

java - 在 Aspect 中访问 HttpServletRequest 对象。提到的两种解决方案之间,哪一个是更好的解决方案

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:21 25 4
gpt4 key购买 nike

在尝试获取 Aspect 中的请求对象时,我找到了两个解决方案。我想知道哪个性能更好。这是详细信息。

我想为“@myAnnotation”注释的所有方法执行 myAspectMethod。因此,在 spring 在方法级别找到 @myAnnotation 的地方,myAspectMethod 将在我使用请求对象执行业务逻辑的地方执行。为了获得请求,我找到了两个解决方案

  1. 在Aspect类中注入(inject)请求对象
    下面

    @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
    }
    }
  2. 通过在带注释的方法中将请求对象作为参数发送并通过接收到的参数列表访问它

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 {
}
  1. 在以上两种不同的请求对象使用方式之间,从性能角度来看,哪种方式更好?这是一个重要的问题,我想知道答案。

  2. 每种方法的其他优缺点是什么。

最佳答案

  1. 我不确定第一种方法是否有效。即使您可以通过这种方式 Autowiring HttpServletRequest,您也必须将方面请求限定在范围内。

  2. 我认为最好的选择是使用 RequestContextHolder:

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    此方法使用已由 Spring 填充的线程本地存储,并且不需要对您的方法签名进行任何更改。

关于java - 在 Aspect 中访问 HttpServletRequest 对象。提到的两种解决方案之间,哪一个是更好的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29803323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com