sping AOP 使用

来源:互联网 发布:淘宝禁止出售的药品 编辑:程序博客网 时间:2024/05/16 03:32

定义接口

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
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 2个月婴儿消化不好怎么办 10月婴儿不吃饭怎么办 9个月宝宝不吃饭怎么办 十个多月的宝宝便秘怎么办 十个多月宝宝便秘怎么办 8个月宝宝过敏怎么办 宝宝二十个月便秘怎么办 7个月宝宝便秘拉不出怎么办 二十六个月宝宝便秘怎么办 八个月宝宝吃鸡蛋过敏怎么办 8个月宝宝 吃盐怎么办 40多天婴儿拉肚怎么办 刚出生婴儿拉肚怎么办 20多天婴儿拉肚怎么办 米汤煮的太稠了怎么办 两岁宝宝不吃蔬菜怎么办 两岁宝宝不爱吃蔬菜怎么办 四个月宝宝头有点歪怎么办 宝宝吃过了还闹怎么办 ddrops d3吃多了怎么办 ddrops d3滴多了怎么办 维生素d滴多了怎么办 ddrops最后滴不出来的怎么办 ddrops一次滴3滴怎么办 小孩子头睡偏了怎么办 7岁儿童头睡偏了怎么办 婴儿后脑睡平了怎么办 六个月宝宝免疫力低怎么办 十个月宝宝食烧怎么办 6个月宝宝感冒了怎么办 5个月宝宝腿短怎么办 5个月宝宝太瘦怎么办 宝宝喝了浓奶粉怎么办 一岁把尿不尿怎么办 五个月的宝宝大便干燥怎么办 婴儿便秘怎么办什么方法最有效 8个月小孩便秘怎么办 1个月新生儿便秘怎么办 新生儿头竖立0分怎么办 20天的宝宝便秘怎么办 出生23天的宝宝便秘怎么办