2010-01-18 119 views
1

試圖找出如何以註釋方式代理我的bean與AOP建議。spring 3 AOP異常建議

我有一個簡單的類

@Service 
public class RestSampleDao { 

    @MonitorTimer 
    public Collection<User> getUsers(){ 
       .... 
     return users; 
    } 
} 

我已創建自定義註解監督執行時間

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

,並建議做一些假的監控

public class MonitorTimerAdvice implements MethodInterceptor { 
    public Object invoke(MethodInvocation invocation) throws Throwable{ 
     try { 
      long start = System.currentTimeMillis(); 
      Object retVal = invocation.proceed(); 
      long end = System.currentTimeMillis(); 
      long differenceMs = end - start; 
      System.out.println("\ncall took " + differenceMs + " ms "); 
      return retVal; 
     } catch(Throwable t){ 
      System.out.println("\nerror occured"); 
      throw t; 
     } 
    } 
} 

現在我可以使用它如果我手動代理這樣的道的實例

AnnotationMatchingPointcut pc = new AnnotationMatchingPointcut(null, MonitorTimer.class); 
    Advisor advisor = new DefaultPointcutAdvisor(pc, new MonitorTimerAdvice()); 

    ProxyFactory pf = new ProxyFactory(); 
    pf.setTarget(sampleDao); 
    pf.addAdvisor(advisor); 

    RestSampleDao proxy = (RestSampleDao) pf.getProxy(); 
    mv.addObject(proxy.getUsers()); 

但我該如何在Spring中設置它,以便我的自定義註釋方法能夠被這個攔截器自動代理?我想注入代理samepleDao而不是真正的一個。這可以做到沒有XML配置?

我認爲應該有可能僅僅註釋我想攔截的方法,並且彈簧DI會代理什麼是必要的。

或者我必須使用aspectj嗎?將提供最簡單的解決方案: - )

非常感謝您的幫助!

回答

3

你還沒有使用AspectJ的,但是你可以使用AspectJ的註解與Spring(見7.2 @AspectJ support):

@Aspect 
public class AroundExample { 
    @Around("@annotation(...)") 
    public Object invoke(ProceedingJoinPoint pjp) throws Throwable { 
     ... 
    } 
} 
+0

感謝的是解決了這個問題: - ) – Art79 2010-01-18 18:27:34