正確配置spring aop,在controller中使用AOP

在controller中使用AOP的問題主要在於如何讓controller可以被檢測到。 
controller和其餘spring bean的區別在於:controller是由mvc定義並在web.xml中的dispatcher中定義的。 

解決方法: 
一、正肯定義controller,(比較通用的作法,沒有特殊狀況的話,大部分應用沒有這個問題) 
    a. 將服務層的類都放在ApplicationCotext-*.xml中定義,在context listener中初始化(注意,任何controller都不該該在這裏出現),要包括<aop:aspectj-autoproxy/>, 在這裏,有沒有proxy-target-class="true" 沒有關係(具體含義參看下文) 
    b. 定義mvc的配置文件,通常是 <<servlet name>>-servlet.xml,通常(也是推薦作法)使用auto scan來定義全部的controller.關鍵步驟來了:這個文件也要加入<aop:aspectj-autoproxy proxy-target-class="true"/>, 必定要添加proxy-target-class="true"! 這是用於通知spring使用cglib而不是jdk的來生成代理方法。 
    c. 另一個事項,controller須要使用@controller註釋,而不是繼承abstract controller。 
    d. 建議使用aspectj來完成aop java

 

package com.kbs.platform.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class RemoteApiLogRecorder {
    //pointcut="execution(* com.abc.service.*.many*(..))",  returning="returnValue"
	@AfterReturning(pointcut="execution(* com.kbs.platform.controller.AppLoginController.*(..))",returning="returnValue")
	public void afterHandle(JoinPoint point,Object returnValue){
		    System.out.println("@AfterReturning:模擬日誌記錄功能...");
	        System.out.println("@AfterReturning:目標方法爲:" + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
	        System.out.println("@AfterReturning:參數爲:" + Arrays.toString(point.getArgs()));
	        System.out.println("@AfterReturning:返回值爲:" + returnValue);
	        System.out.println("@AfterReturning:被織入的目標對象爲:" + point.getTarget());
	}
}
相關文章
相關標籤/搜索