2015-12-03 122 views
-1

我已經成功地使用Spring應用程序的AOP,但令人驚訝的是我堅持一個簡單的java項目。現在我試圖實現非常簡單的AOP Java應用程序,但它不起作用。這裏是基本的類:簡單的java應用程序的AOP

import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 

@Aspect 
public class MySimpleLoggerAspect { 

    @Around("@annotation(TimeableMetric)") 
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable { 
     System.out.println("myTrace:before call "); 

     Object retVal = null; 
     try { 
      retVal = joinPoint.proceed(); 
     } finally { 
      System.out.println("myTrace:after call "); 
     } 
     return retVal; 
    } 
} 

public class SampleClass { 

    @TimeableMetric 
    public String doService(String in){ 
     System.out.println("inside Service"); 
     return in; 
    } 
} 

public class Tester { 
    public static void main(String[] args) { 
     System.out.println(new SampleClass().doService("Hello World")); 
    } 
} 


import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

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

} 

正如你可以看到它是非常簡單的應用程序與4個類。 IntelliJ檢測AOP建議是正確的,但在運行應用程序時會被忽略。我確信有一個我無法察覺的錯誤。 請幫忙!

+0

您編寫了這段代碼並試圖運行它(告訴我們如何運行它)。你爲什麼這樣寫,並以任何方式運行,並期望它做你想要的? (這些問題的答案會表明你對使用AspectJ做了一些研究。) –

+0

我可以使用aop.xml配置編寫它,但我認爲它不是移動的。所以,我更喜歡使用註釋來指出方法建議的方法。爲什麼我以這種方式實施?因爲類似的東西在Spring引導項目下工作。我如何運行它?從主要方法。 –

+0

所以你只是'java測試器'? –

回答

1

的代碼是好的,對我來說,控制檯日誌是這樣的:

myTrace:before call 
myTrace:before call 
inside Service 
myTrace:after call 
myTrace:after call 
Hello World 

也許你從Spring AOP的使用只有一次攔截的切入點@annotation(TimeableMetric),但在相反的Spring AOP只知道execution()切入點,AspectJ還支持call()切入點。所以,如果你改變你的切入點@annotation(TimeableMetric) && execution(* *(..)),日誌變爲:

myTrace:before call 
inside Service 
myTrace:after call 
Hello World 

至於這個問題得到應用如何等方面,需要

  • 編譯AspectJ編譯AJC應用然後
  • 在類路徑上使用AspectJ運行時aspectjrt.jar運行它。
+0

謝謝Kriegaex,這非常有幫助。 我已經配置我的IntelliJ使用Ajca進行編譯nd它完美的工作! –