Spring AOP實戰

AOP(Aspect Orient Programming),面向切面編程,做爲面向對象的一種補充,用於處理系統中分佈於各個模塊的橫切關注點,好比事務管理、日誌、緩存等等。spring

AOP實現的關鍵在於AOP框架自動建立的AOP代理,AOP代理主要分爲靜態代理動態代理編程

  • 靜態代理的表明爲,AspectJ
  • 動態代理,則以Spring AOP爲表明

靜態代理,在編譯期實現,動態代理是運行期實現緩存

  • 靜態代理,是編譯階段生成AOP代理類,也就是說生成的字節碼就已織入了加強後的AOP對象;
  • 動態代理,不會修改字節碼,而是在內存中臨時生成一個AOP對象,該AOP對象包含了目標對象的所有方法,而且在特定的切點作了加強處理,並回調原對象的方法

本文主要介紹Spring AOP的兩種代理實現方式:JDK動態搭理和CGLIB動態代理框架

  • JDK動態搭理,經過反射來接收被代理的類,而且要求被代理的類必須實現一個接口。JDK動態代理的核心是InvocationHandler接口和Proxy類測試

  • 若是目標類沒有實現接口,那麼Spring AOP會選擇使用CGLIB來動態代理目標類。CGLIB,是一個代碼生成的類庫,能夠在運行時動態的生成某個類的子類。注意,CGLIB經過繼承的方式實現動態代理,所以若是某個類被標記爲final,那麼它是沒法使用CGLIB作動態代理的,諸如private的方法也是不能夠做爲切面的。spa

直接使用Spring AOP

  • xml配置文件中需開啓**<aop:aspectj-autoproxy />**
  • 定義基於註解的Advice:@Aspect,@Component,@Pointcut,@Before,@Around,@After。。。
  1. 配置文件開啓AOP註解
<aop:aspectj-autoproxy />
  1. 基於註解的Advice
@Aspect
@Component
public class MonitorAdvice {
        @Pointcut("execution(* com.demo.modul.user.service.Speakable.*(..))")
	public void pointcut() {}
	
	@Around("pointcut()")
	public void around(ProceedingJoinPoint jp) throws Throwable {
		MonitorSession.begin(jp.getSignature().getName());
		
		
		jp.proceed();
		
		MonitorSession.end();
	}
}
  1. 測試:
public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-annotation-aop.xml");  
        /*AnnotationBusiness business = (AnnotationBusiness) context.getBean("annotationBusiness");  
        business.delete("JACK");  */
		
		Speakable business = (Speakable) context.getBean("personSpring");  
        business.sayBye();
	}

基於JDK動態代理

相關文章
相關標籤/搜索