2013-06-05 44 views
1

也許標題「can annotation get context object?」是不正確的,但我不知道如何給它一個正確和清晰的。可以註釋獲取上下文對象嗎?

我使用Spring AOP的+ Java的註釋保存日誌,這裏是我的代碼:

CategoryAction.java:

@ServiceTracker(methodDesp="save category, category name:"+this.category.getName()) 
public String save() throws Exception 
{ 
    this.categoryService.save(this.category); 
    this.setJsonDataSimply(null); 
    return "save"; 
} 

TrackAdvice.java:

public Object trackAround(ProceedingJoinPoint point) throws Throwable 
{ 
    String log = "success"; 
    ServiceTracker tracker = null; 
    Method method = null; 
    AbstractAction action = null; 
    try 
    { 
     Object result = point.proceed(); 
     action = (AbstractAction) point.getTarget(); 
     MethodSignature signature = (MethodSignature) point.getSignature(); 
     method = signature.getMethod(); 
     tracker = method.getAnnotation(ServiceTracker.class); 
     return result; 
    } 
    catch (Exception e) 
    { 
     log = e.getMessage(); 
     throw e; 
    } 
    finally 
    { 
     if (tracker != null) 
     { 
      String userId = (String) ActionContext.getContext().getSession().get(Constant.USERID); 
      if (userId == null) 
      { 
       userId = "unknown"; 
      } 
      TrackLog t = new TrackLog(); 
      t.setWhen(new Date()); 
      t.setUserId(userId); 
      t.setResult(log); 
      t.setMethodName(action.getClass().getCanonicalName() + "." + method.getName()); 
      t.setMethodDesp(tracker.methodDesp()); 
      this.trackService.save(t); 
     } 
    } 
} 

ServiceTracker是我自己註釋,在我的TrackAdvice類中,我得到當前的執行方法,如果方法有ServiceTracker註釋,則保存methodDesp註釋到數據庫。

現在問題是methodDesp在註釋中是動態的,我想獲取this對象並檢索它的category屬性。

看來,Java註解不支持這個,也許它支持,但我不知道如何。

回答

2

你可以做的是在註解值中使用某種表達式語言,然後在你的建議代碼中運行一些解釋器。使用SPEL一個例子看起來是這樣的:

@ServiceTracker(methodDesp="save category, category name: #{category.name}") 

而在你的忠告代碼,就可以提取表達令牌,使用一個SpelExpression的,並通過它的target引用作爲根對象(你可能要檢查在SPEL API中提供了用於支持用例的開箱即用功能)。

+0

非常感謝。表達式是這樣的:'methodDesp =''保存類別,類別名稱:'。concat(category.name)「',我剛剛測試過。 – hiway

2

看來,Java的註釋不支持此

你是正確的 - 沒有辦法用純Java來做到這一點。

的原因是,因爲註釋是靜態元數據被接線成和定義在編譯時(以在運行時只存在this開始,而不是編譯時)。

換句話說,有些類的動態註解方法沒有直接的方法,因爲它的值必須在編譯時靜態解析。

然而,從技術上講,有一種方法可以做到像你想要的。我所說的是使用javassist來在運行時操作或創建類(以及應用於它們的註釋)。但要警告的是,這是相當不吉利的方式,我通常不會推薦去那裏。

相關問題