加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 在Aspect中访问HttpServletRequest对象.哪一个是提到的

发布时间:2020-12-15 01:39:47 所属栏目:大数据 来源:网络整理
导读:在尝试获取Aspect中的请求对象时,我找到了两个解决方案.我想知道哪个更好的表现.这是详细信息. 我想为@myAnnotation注释的所有方法执行myAspectMethod.所以Spring在方法级找到@myAnnotation,myAspectMethod将在我使用请求对象执行业务逻辑的地方执行.为了得

在尝试获取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 {
}

>在两种不同的请求对象使用方式之间,从性能角度看哪一种更好?这是一个重要的问题,我想知道答案.
>每种方法的其他优缺点是什么?

最佳答案
>我不确定第一种方法是否有效.即使您可以通过这种方式自动装配HttpServletRequest,您也必须使用方面请求范围.
>我认为最好的选择是使用RequestContextHolder:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读