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

java– 在Aspect中访问HttpServletRequest对象.哪一个是提到的两个解决方案之间的更好的解,第1张

概述在尝试获取Aspect中的请求对象时,我找到了两个解决方案.我想知道哪个更好的表现.这是详细信息.我想为'@myAnnotation'注释的所有方法执行myAspectMethod.所以Spring在方法级找到@myAnnotation,myAspectMethod将在我使用请求对象执行业务逻辑的地方执行.为了得到请求我找到了两个解决方案>在Aspec

在尝试获取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")@MyAnnotationpublic Object myAnnotatedMethod(**httpServletRequest request**){//....some business logic}@Aspectpublic 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填充的线程本地存储,并且不需要对方法签名进行任何更改. 总结

以上是内存溢出为你收集整理的java – 在Aspect中访问HttpServletRequest对象.哪一个是提到的两个解决方案之间的更好的解全部内容,希望文章能够帮你解决java – 在Aspect中访问HttpServletRequest对象.哪一个是提到的两个解决方案之间的更好的解所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1265216.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存