Spring AOP是代理模式的經典實現,代理模式的作用就是把一些目標類沒有的功能附加到代理類上,然后在代理類上執行目標類的方法,這給客戶端的一個假象,好像這些新加功能在本來就在目標類上。Spring AOP使用的動態代理技術,JDK和CGLIB,Spring AOP優先選擇JDK,假如不符合JDK代理的要求(目標類必須實現一個接口),就會嘗試使用CGLIB,如果再不符合CGLIB的要求(目標類不能是final類型),那么就不能使用Spring AOP技術。下面是一個基于XML配置的一個簡單但不是有用的例子。
-
目標類代碼
public interface Mobile {
public void call();
}public class Xiaomi implements Mobile{ @Override public void call() { System.out.println("小米手機打電話"); } }
切面類代碼
public class MobileAspect {
//一個前置通知
public void before(){
System.out.println("開機");
}
}XML配置
<bean id="xiaomi" class="annotation.Xiaomi"/>
<bean id="aspect" class="annotation.MobileAspect"/>
<aop:config>
<aop:pointcut expression="execution(* annotation.Xiaomi.*(..))" id="pointcut"/>
<aop:aspect ref="aspect">
<aop:before method="before" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>測試類代碼:
public class AopAnnotationDemo {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-introduction.xml");
Mobile mi = (Mobile) context.getBean("xiaomi");
System.out.println(mi.getClass().getSimpleName());//輸出的是$Proxy2,說明我們調用不是Xiaomi類的對象,而是JDK動態代理生成的代理類,這個代理類在執行Xiaomi類對象上的方法時,會想執行切面類中的before()方法。
mi.call();
}
}
Spring AOP也支持注解的方式。