Spring AOP 中@Pointcut的用法

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)

 括号中各个pattern分别表示修饰符匹配(modifier-pattern?)、返回值匹配(ret-type-pattern)、类路径匹配(declaring-type-pattern?)、方法名匹配(name-pattern)、参数匹配((param-pattern))、异常类型匹配(throws-pattern?),其中后面跟着“?”的是可选项。

---------------------------------万能分隔线---------------------------------------

returning type pattern,name pattern, and parameters pattern是必须的.
ret-type-pattern:可以为*表示任何返回值,全路径的类名等.
name-pattern:指定方法名,*代表所以,set*,代表以set开头的所有方法.
parameters pattern:指定方法参数(声明的类型),(..)代表所有参数,(*)代表一个参数,(*,String)代表第一个参数为任何值,第二个为String类型.

---------------------------------万能分隔线---------------------------------------

现在来看看几个例子:
1)execution(* *(..))
表示匹配所有方法
2)execution(public * com. savage.service.UserService.*(..))
表示匹配com.savage.server.UserService中所有的公有方法
3)execution(* com.savage.server..*.*(..))
表示匹配com.savage.server包及其子包下的所有方法

 Pointcut定义时,还可以使用&&||!

运算,如:
java 代码
 
@Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
private void logSender(){}
@Pointcut("execution(* com.savage.aop.MessageReceiver.*(..))")
private void logReceiver(){}
@Pointcut("logSender() || logReceiver()")
private void logMessage(){}
 
这个例子中,logMessage()将匹配任何MessageSender和MessageReceiver中的任何方法。
还可以将一些公用的Pointcut
放到一个类中,以供整个应用程序使用,如:
java 代码
 
package com.savage.aop;
import org.aspectj.lang.annotation.*;
public class Pointcuts {
@Pointcut("execution(* *Message(..))")
public void logMessage(){}
@Pointcut("execution(* *Attachment(..))")
public void logAttachment(){}
@Pointcut("execution(* *Service.*(..))")
public void auth(){}
}
 
在使用这些Pointcut时,指定完整的类名加上Pointcut
签名就可以了,如:
java 代码
package com.savage.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class LogBeforeAdvice {
@Before("com.sagage.aop.Pointcuts.logMessage()")
public void before(JoinPoint joinPoint) {
System.out.println("Logging before " + joinPoint.getSignature().getName());
}
}
 
当基于 XML Sechma实现 Advice时,如果 Pointcut需要被重用,可以使用 <aop:pointcut></aop:pointcut>来声明 Pointcut,然后在需要使用这个 Pointcut的地方,用 pointcut-ref引用就行了,如:
xml 代码
<aop:config>
<aop:pointcut id="log"
expression="execution(* com.savage.simplespring.bean.MessageSender.*(..))"/>
<aop:aspect id="logging" ref="logBeforeAdvice">
<aop:before pointcut-ref="log" method="before"/>
<aop:after-returning pointcut-ref="log" method="afterReturning"/>
</aop:aspect>
</aop:config>
 

猜你喜欢

转载自843977358.iteye.com/blog/2251959