Spring 【Aspectj】进行AOP开发 (【注解】方式)

 

1.被监控的接口,及其实现类(0侵入)

/**
 * 演员
 *
 */
public interface Performer {
    public void show();
}

public class Singer implements Performer {

    @Override
    public void show(){
        System.out.println("我是个歌手!");
//        String s = null;
//        s.length();
    }
}
View Code

2.切片类

/**
 *    观众
 */
@Aspect   //切片
public class Audience {

    //坐下
    //@Before("execution (* aspectj.Performer.*(..))")
    public void takeSeats(JoinPoint jp){
        System.out.println("method : " + jp.getSignature().getName());
        System.out.println("target : " + jp.getTarget());  //  目标对象
        
        //代理对象(toString)值与getTarget一致,为直接toString()方法
        System.out.println("this : " + jp.getThis());      
        System.out.println("args : " + jp.getArgs());
    }
    
    //关手机
    //@Before("execution (* aspectj.Performer.*(..))")
    public void turnOffCellPhone(){
        System.out.println("turnOffCellPhone");
    }
    
    //退票
    //throwing 指定接收异常信息的参数
    //@AfterThrowing(pointcut="execution (* aspectj.Performer.*(..))",throwing="e")
    public void demandRefund(Exception e){
        System.out.println("退票");
        System.out.println("出事了  : ");
    }
    
    //鼓掌(抛异常则不执行)
    //returning 指定接收返回值的参数
    //@AfterReturning(pointcut="execution (* aspectj.Performer.*(..))",returning="ret")
    public void applaud(JoinPoint jp,Object ret){
        System.out.println("applaud");
        System.out.println("返回值为: " + ret);
    }
    
    //回家
    //@After("execution (* aspectj.Performer.*(..))")
    public void goHome(){
        System.out.println("回家...");
    }
    
    //观看  (包含以上的所有行为)
    @Around("execution (* aspectj.Performer.*(..))")
    public Object doWatch(ProceedingJoinPoint pjp){
        
        //@Before
        System.out.println("就座");
        System.out.println("关手机");
        
        Object res = null;
        //调用目标对象的方法
        try {
            res = pjp.proceed();
            
            //@AfterReturning
            System.out.println("鼓掌...");
        }
        catch (Throwable e) {
            //@AfterThrowing
            System.out.println("出事了 !" + e.getMessage());
        }finally{
            //@After
            System.out.println("回家");
        }
        
        //@AfterReturning
        return res;
    }
}
View Code

3.配置文件

<!-- 歌手演员 -->
<bean id="singer" class="aspectj.Singer"/>

<!-- 观众(通知) -->
<bean class="aspectj.Audience"/>

<!-- 注解生效  -->
<aop:aspectj-autoproxy/>

 

附:

posted @ 2013-12-16 21:34  聆听自由  阅读(243)  评论(0编辑  收藏  举报