Spring AOP 中@Pointcut的用法
本文内容纲要:
格式:
execution(modifiers-pattern?ret-type-patterndeclaring-type-pattern?name-pattern(param-pattern)throws-pattern?)
括号中各个pattern分别表示:
- 修饰符匹配(modifier-pattern?)
- 返回值匹配(ret-type-pattern)可以为*表示任何返回值,全路径的类名等
- 类路径匹配(declaring-type-pattern?)
- 方法名匹配(name-pattern)可以指定方法名或者*代表所有,set*代表以set开头的所有方法
- 参数匹配((param-pattern))可以指定具体的参数类型,多个参数间用“,”隔开,各个参数也可以用“*”来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(*,String)表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(..)表示零个或多个任意参数
- 异常类型匹配(throws-pattern?)
- 其中后面跟着“?”的是可选项
现在来看看几个例子:
1)execution(**(..))
//表示匹配所有方法
2)execution(public*com.savage.service.UserService.*(..))
//表示匹配com.savage.server.UserService中所有的公有方法
3)execution(*com.savage.server..*.*(..))
//表示匹配com.savage.server包及其子包下的所有方法
在Spring2.0中,Pointcut的定义包括两个部分:Pointcut表示式(expression)和Pointcut签名(signature)
//Pointcut表示式
@Pointcut("execution(*com.savage.aop.MessageSender.*(..))")
//Point签名
privatevoidlog(){}
然后要使用所定义的Pointcut时,可以指定Pointcut签名
如下:
@Before("og()")
这种使用方式等同于以下方式,直接定义execution表达式使用
@Before("execution(*com.savage.aop.MessageSender.*(..))")
Pointcut定义时,还可以使用&&、||、!这三个运算
@Pointcut("execution(*com.savage.aop.MessageSender.*(..))")
privatevoidlogSender(){}
@Pointcut("execution(*com.savage.aop.MessageReceiver.*(..))")
privatevoidlogReceiver(){}
@Pointcut("logSender()||logReceiver()")
privatevoidlogMessage(){}
这个例子中,logMessage()将匹配任何MessageSender和MessageReceiver中的任何方法。
还可以将一些公用的Pointcut放到一个类中,以供整个应用程序使用,如下:
packagecom.savage.aop;
importorg.aspectj.lang.annotation.*;
publicclassPointcuts{
@Pointcut("execution(**Message(..))")
publicvoidlogMessage(){}
@Pointcut("execution(**Attachment(..))")
publicvoidlogAttachment(){}
@Pointcut("execution(**Service.*(..))")
publicvoidauth(){}
}
在使用上面定义Pointcut时,指定完整的类名加上Pointcut签名就可以了,如:
packagecom.savage.aop;
importorg.aspectj.lang.JoinPoint;
importorg.aspectj.lang.annotation.*;
@Aspect
publicclassLogBeforeAdvice{
@Before("com.sagage.aop.Pointcuts.logMessage()")
publicvoidbefore(JoinPointjoinPoint){
System.out.println("Loggingbefore"+joinPoint.getSignature().getName());
}
}
当基于XMLSechma实现Advice时,如果Pointcut需要被重用,可以使用aop:pointcut</aop:pointcut>来声明Pointcut,然后在需要使用这个Pointcut的地方,用pointcut-ref引用就行了,如:
<aop:config>
<aop:pointcutid="log"expression="execution(*com.savage.simplespring.bean.MessageSender.*(..))"/>
<aop:aspectid="logging"ref="logBeforeAdvice">
<aop:beforepointcut-ref="log"method="before"/>
<aop:after-returningpointcut-ref="log"method="afterReturning"/>
</aop:aspect>
</aop:config>
另外,除了execution表示式外,还有within、this、target、args等Pointcut表示式
本文内容总结:
原文链接:https://www.cnblogs.com/liaojie970/p/7883687.html