也許標題「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註解不支持這個,也許它支持,但我不知道如何。
非常感謝。表達式是這樣的:'methodDesp =''保存類別,類別名稱:'。concat(category.name)「',我剛剛測試過。 – hiway