springAOP学习笔记

springAOP是面向切面编程,它一共有6个概念

①JoinPoint(连接点)所谓连接点是指那些被拦截到的点,在spring中这些点指的是方法,因为spring只支持方法类型的连接点

②PointOut(切入点)所谓切入点是指我们要对哪些JoinPoint进行拦截的定义

③Advice通知/增强,拦截到JoinPoint之后所做的事情就是通知,通知的类型有前置通知,后置通知,异常通知,环绕通知,最终通知
④Introduction引界是一种特殊的通知,在不改变类的前提下,Introduction可以在运行期为类动态的添加一些方法
⑤Target(目标对象)植入Advice的目标对象

再通过代码实验一下

新建一个Account接口及其实现类

public interface Account {
    public void save();
   
}

public class AccountImpl implements Account {
    public void save(){
        System.out.println("省了100元");
    }
   
}

然后再新建一个拦截类

public class Aspect {
    public void before(){
        System.out.println("前置通知");
    }
    public void afterReturn(){
        System.out.println("后置通知");
    }
    public void afterThrow(){
        System.out.println("异常通知");
    }
    public void after(){
        System.out.println("最终通知");
    }
}


最后配置xml文件

 <bean id="Account" class="Test4.AccountImpl"></bean>
        <bean id="Aspect" class="Test4.Aspect"></bean>
            <aop:config>
             
                <aop:aspect id="ascpect" ref="Aspect">
                
<aop:before method="before" pointcut="execution(public void Test4..AccountImpl.save())"></aop:before>

<aop:after-returning method="afterReturn" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after-returning>
             
<aop:after-throwing method="afterThrow" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after-throwing>
                
<aop:after method="after" pointcut="execution(public void Test4..AccountImpl.save())"></aop:after>

                </aop:aspect>
            </aop:config>

最后测试得到结果

public class Test {
    public  static void main(String[]args){
       ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        Account account=(Account)context.getBean("Account");
        account.save();
    }
}
/*前置通知
省了100元
后置通知
最终通知*/

除此之外AOP还有环绕通知,我们也可以通过方法来配置通知,就是调用ProceedingJoinPoint接口即可


public class Around  {

    public void around(ProceedingJoinPoint pjp){
        try{
            System.out.println("前置通知");
         
            pjp.proceed();
            System.out.println("后置通知");
        }catch (Throwable e){
          System.out.println("异常通知");
        }
        finally {
            System.out.println("最终通知");
        }

    }
}

结果和上面一样,还有就是异常通知和后置通知是不能一起出现的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值