sping AOP 使用

6 篇文章 0 订阅

定义接口

public interface Performer {


void perform(List ls);
}

实现接口

@Service
public class Drama implements Performer {


public void perform(List ls) {

// TODO Auto-generated method stub
 for (int i = 0; i < 1000; i++) {
           System.out.println("话剧正在进行中——"+ls.get(2).toString());
       }
 
}


}


切面拦截类


@Service
public class Audience {
public void takeSeats() throws Throwable {

        // 节目开始之前
        System.out.println("演出前——观众开始入座");
    }


    public void turnOffCellPhones() {
        // 节目开始之前
        System.out.println("演出前——观众关机或静音");
    }


    public void applaud() {
        // 节目成功结束之后
        System.out.println("成功演出很成功——观众鼓掌:啪啪啪");
    }


    public void demandRefund() {
        // 节目表演失败之后
        System.out.println("节目演出很失败——切!一点都不好看,我们要求退钱!");
    }
    public Object watchPerformance(ProceedingJoinPoint point) {
        try {
       
        Object[] args = point.getArgs();


         if (args != null && args.length > 0 && args[0].getClass() == ArrayList.class) {


          List lt= (List)args[0];
         
          lt.add("panshuyao");//向参数LIst中增加一个值
          args[0]=lt;


         }
        Object returnValue = point.proceed(args);//执行方法,必须写此方法否则将会不运行代码
//System.out.println(args[0]+"********");
         //用改变后的参数执行目标方法


      return returnValue;
        } catch (Throwable e) {
        e.printStackTrace();
            System.out.println("节目演出很失败——切!一点都不好看,我们要求退钱!");
            return -1;
        }
    }


}


spring 配置


pointcut 设置需要进行切面的类

aspect 拦截类

before 运行目标方法前

after-returning 成功后

after-throwing 失败后

around 引介增强 可以修改传递的参数和返回的结果

<aop:config>
<aop:pointcut expression="execution(* study.com.domeaop.Performer.perform(..))" id="pointcut"></aop:pointcut>
  <aop:aspect ref="audience">
  <aop:before pointcut-ref="pointcut" method="takeSeats"/>
         <aop:before pointcut-ref="pointcut" method="turnOffCellPhones"/>
        <aop:after-returning pointcut-ref="pointcut" method="applaud"/>
        <aop:after-throwing pointcut-ref="pointcut" method="demandRefund"/>
        <aop:around pointcut-ref="pointcut" method="watchPerformance"/> 
  </aop:aspect>
</aop:config>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值