AOP(Aspect Orient Programming),面向切面編程,做爲面向對象的一種補充,用於處理系統中分佈於各個模塊的橫切關注點,好比事務管理、日誌、緩存等等。spring
AOP實現的關鍵在於AOP框架自動建立的AOP代理,AOP代理主要分爲靜態代理和動態代理:編程
靜態代理,在編譯期實現,動態代理是運行期實現。緩存
本文主要介紹Spring AOP的兩種代理實現方式:JDK動態搭理和CGLIB動態代理框架
JDK動態搭理,經過反射來接收被代理的類,而且要求被代理的類必須實現一個接口。JDK動態代理的核心是InvocationHandler接口和Proxy類測試
若是目標類沒有實現接口,那麼Spring AOP會選擇使用CGLIB來動態代理目標類。CGLIB,是一個代碼生成的類庫,能夠在運行時動態的生成某個類的子類。注意,CGLIB經過繼承的方式實現動態代理,所以若是某個類被標記爲final,那麼它是沒法使用CGLIB作動態代理的,諸如private的方法也是不能夠做爲切面的。spa
<aop:aspectj-autoproxy />
@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(); } }
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(); }