2015-01-02 50 views
2

我想在執行方法和方法結束時記錄日誌。爲此,我有一個簡單的方面用於記錄方法開始/結束的Java方面

@Aspect 
public class StartEndLogger { 
    @Around("execution(* *(..)) && @annotation(StartEndLog)") 
    public Object around(ProceedingJoinPoint point) { 
    Object result = null; 
    System.out.println("start"); 
    try { 
     result = point.proceed(); 
    } catch (Throwable e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    System.out.println("end"); 
    return result; 
    } 
} 

然後定義註解:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ ElementType.METHOD, ElementType.TYPE }) 
public @interface StartEndLog { 

} 

出於測試我有:

@StartEndLog 
public static void main(String[] args) throws IOException { 
} 

事情是,該方面不攔截方法執行(運行時沒有進入方面)。我應該以某種方式註冊此註釋的方面嗎?我不使用任何Spring。

+0

你見過這個嗎? http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html – maksimov

+0

如果註釋具有包名稱,則需要在註釋樣式切入點中使用完全限定名稱。如果您使用本地語法,則不需要,那麼您只需使用導入。 – kriegaex

回答

0

你可以試試嗎?

在你煲的「META-INF/aop.xml文件」的文件,包括您的看點類的全路徑

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> 
<aspectj> 
    <weaver> 
     <include within="somepackage.StartEndLogger " /> 
    </weaver> 
    <aspects> 
     <concrete-aspect name="MyLoggingAspect" 
     extends="somepackage.StartEndLogger"> 
      <pointcut name="around_logging" expression="execution(* *(..)) && @annotation(StartEndLog)"/> 
     </concrete-aspect> 
    </aspects> 
</aspectj> 

如果您正在使用Spring框架,註釋類也有「@Component 」。

這是Spring的摘錄:

你可以註冊方面類作爲普通豆在Spring XML配置 ,或者通過使用classpath掃描自動檢測它們 - 只是 象其他Spring管理的bean。然而,請注意@Aspect 註釋不足以在類路徑中進行自動檢測:對於 該目的,您需要添加一個單獨的@Component註釋(或 或者定製原型註釋,該註釋符合 的規定,Spring的規則組件掃描儀)。

+0

謝謝,但如果我不使用Spring框架? – Mejmo

+0

@Mejmo對不起。我已經更新了答案。 –

相關問題