2015-04-22 148 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