AOP的advisor了解

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可以控制围绕的次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值