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

时间:2023-03-09 09:32:06
spring aop配置及用例说明(3)

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

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

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

上面的代理对象就是指("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标签,这个里面提供了一个代理的对象。如果用这个,就可以把原来的值给替换掉

 @Around("execution(public * com.bing.test..*.sayHello(..))&&args(name)")
public Object around(ProceedingJoinPoint pjp,String name) throws Throwable { System.out.println("around Method");
// start stopwatch
if(name instanceof String){ name="@"+name;
}
Object retVal = pjp.proceed(new Object[]{name});
// stop stopwatch return retVal;
}