spring aop配置及用例说明(3)

欢迎转载交流:http://www.cnblogs.com/shizhongtao/p/3476336.html                       

1.这里说一下aop的@Around标签,它提供了在方法开始和结束,都能添加用户业务逻辑的aop方法,@Around标签的方法包含一个 ProceedingJoinPoint 对象作为参数。其实你可以把这个对象理解为一个代理对象。当ProceedingJoinPoint 执行proceed()方法时候,也就会调用切面对象的方法。可能有点抽象。

 1 @Aspect
 2 public class AroundExample {
 3 
 4   @Around("com.xyz.myapp.SystemArchitecture.businessService()")
 5   public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
 6     // 开始执行被加入切面的方法
 7     Object retVal = pjp.proceed();
 8     // retVal就是代理对象(被切面对象)的返回值
 9    return retVal;
10   }
11 
12 }

上面的代理对象就是指("com.xyz.myapp.SystemArchitecture.businessService()")这个切入点的所有方法。

2.下面在说一下如何获得切入点的参数。

比如我的manager对下有一个sayHello方法,他接受一个String类型的属性。

public void sayHello(String name) {
        System.out.println("Hello " + name);
    }

如果我们在切入点配置想要得到这个name的值可以这样写:

// 表示在方法前面执行,name表示得到参数,而sayHllo中的"String"限定了只对有一个String类型的sayHello方法起作用
    @Before("execution(public * com.bing.test..*.sayHello(String))&&args(name)")
    public void before(String name) {
        System.out.println(name);
         name="@"+name;//这个并不能更改sayHello中的参数值,因为Sting是值传递。如果你想更改的话,可以把原来参数类型改为引用类型
         System.out.println(name);
        System.out.println("before Method");
    }

 前面我们说到了@Around标签,这个里面提供了一个代理的对象。如果用这个,就可以把原来的值给替换掉

 1 @Around("execution(public * com.bing.test..*.sayHello(..))&&args(name)")
 2     public Object around(ProceedingJoinPoint pjp,String name) throws Throwable {
 3         
 4         System.out.println("around Method");
 5         // start stopwatch
 6         if(name instanceof String){
 7             
 8             name="@"+name;
 9         }
10         Object retVal = pjp.proceed(new Object[]{name});
11         // stop stopwatch
12         
13         return retVal;
14     }

 

 

posted @ 2013-12-16 11:06  bingyulei  阅读(609)  评论(0编辑  收藏  举报