2015-04-22 150 views
4

虽然试图获得请求对象的方面,我发现了两个解决方案。我想知道哪一个更好一些。这里是细节。在Aspect中访问HttpServletRequest对象。哪一个更好的解决方案提到两个解决方案

我想对'@myAnnotation'注解的所有方法执行myAspectMethod。所以,当Spring发现方法级别的@myAnnotation时,myAspectMethod将在我使用请求对象执行业务逻辑的地方执行。为了得到要求我发现了两个解决方案

  1. 进样请求对象的看点类像
    下面

    @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. 通过发送请求的对象作为注解的方法参数和访问它直通参数列表收到

访问请求方面

@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. 每种方法的其他优点和缺点是什么。

回答

7
  1. 我不知道的是,第一种方法的工作原理。即使您以这种方式自动装配HttpServletRequest,您也必须让您的方面请求范围。

  2. 我认为最好的办法是使用RequestContextHolder

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

    此方法使用已经由Spring填充的线程本地存储,不需要在你的方法签名的任何变化。

+0

谢谢@axtavt! 对于解决方案#1,我认为类似的东西,即如何将请求对象注入单例方面。当我实现并通过具有不同标题值的不同请求时,每当我获得期望值时。这意味着每个请求对象可以设置为单身bean。看起来春天按照范围优雅地处理它。这里是我遇到的优秀文章 [http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection] – Siddhant