AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
- 预编译方式:AspectJ
- 运行期动态代理(JDK动态代理、CGlib动态代理):SpringAOP、JBossAOP
<bean id="moocAspect" class="com.imooc.aop.schema.advice.MoocAspect"></bean>
<bean id="aspectBiz" class="com.imooc.aop.schema.advice.biz.AspectBiz"></bean>
<aop:config>
//切面类
<aop:aspect id="moocAspectAOP" ref="moocAspect">
//切点
<aop:pointcut expression="execution(* com.imooc.aop.schema.advice.biz.*Biz.*(..))" id="moocPiontcut"/>
//在运行切点前运行,不影响切点的运行
<aop:before method="before" pointcut-ref="moocPiontcut"/>
//在切点运行完正常返回后运行,当切点返回异常时,该方法不运行
<aop:after-returning method="afterReturning" pointcut-ref="moocPiontcut"/>
//在切点运行返回异常时运行
<aop:after-throwing method="afterThrowing" pointcut-ref="moocPiontcut"/>
//切点运行完后运行,在after-returning前运行
<aop:after method="after" pointcut-ref="moocPiontcut"/>
//方法第一个参数必须为ProceedingJoinPoint pjp
<aop:around method="around" pointcut-ref="moocPiontcut"/>
//下面代码解释:匹配方法参数类型必须为(String,int)并且参数名必须为(bizName, times);好处是可以在切面方法中使用传入切点的参数
<aop:around method="aroundInit" pointcut="execution(* com.imooc.aop.schema.advice.biz.AspectBiz.init(String, int)) and args(bizName, times)"/>
//通过declare-parents可以让匹配的类获得一个新的父类
<aop:declare-parents types-matching="com.imooc.aop.schema.advice.biz.*(+)"
implement-interface="com.imooc.aop.schema.advice.Fit"
default-impl="com.imooc.aop.schema.advice.FitImpl"/>
</aop:aspect>
</aop:config>
<aop:around />
public Object around(ProceedingJoinPoint pjp) {
Object obj = null;
try {
System.out.println("MoocAspect around 1.");
obj = pjp.proceed();
System.out.println("MoocAspect around 2.");
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
public Object aroundInit(ProceedingJoinPoint pjp, String bizName, int times) {
System.out.println(bizName + " " + times);
Object obj = null;
try {
System.out.println("MoocAspect aroundInit 1.");
obj = pjp.proceed();
System.out.println("MoocAspect aroundInit 2.");
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
切点:
public class AspectBiz {
public void biz() {
System.out.println("AspectBiz biz.");
// throw new RuntimeException();
}
public void init(String bizName, int times) {
System.out.println("AspectBiz init : " + bizName + " " + times);
}
}
schema-definited aspects 只支持单例模式
通过advisors可以控制围绕的次数