springAOP 的pointcut

时间:2023-03-08 15:37:51
 <bean id="amqFilter" class="com.xxx.hotel.base.aspectj.AmQConsumerFilter"/>

    <aop:config proxy-target-class="true">
        <aop:aspect ref="amqFilter">
            <aop:before method="beforeOnMessage" arg-names="message"
                        pointcut="execution(* xxx.amq.MessageListener.onMessage(..)) and args(message)"/>
        </aop:aspect>
    </aop:config>

那么pointcut后边的表达式说明了哪些方法需要被aop所执行,可以有args()  @args()   execution()   target()  @target()  @annotation等来定义或组合(&& , || , !)

其中比较常见的是execution,例子如下:

任意公共方法的执行

execution(public * *(..))

任意一个以get开头的方法的执行

execution(* get*(..))

hotelService接口的任意方法

execution(* com.balfish.hotel.service.HotelService.*(..))

service包里的任意方法的执行

execution(* com.balfish.hotel.service.*.*(..))

service包和所有子包里的任意类的任意方法的执行

execution(* com.balfish.hotel.service..*.*(..)) 

总结:靠近(..)的是方法,靠近.*(..)的是类或接口

Pointcut 可以通过Java注解和XML两种方式配置,如下所示:

<aop:config>
    <aop:aspectref="aspectDemo">
        <aop:pointcutid="pointcut"expression="execution(* com.balfish.spring.aop.pointcut..JoinPointTest.*(..))"/>
        <aop:before pointcut-ref="pointcut" method="beforeAdvice" />
    </aop:aspect>
</aop:config>

@Component
@Aspect
public class AspectDemo {
    //@Pointcut("execution(* com.balfish.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
    //@Pointcut("within(com.balfish.spring.aop.pointcutexp..*)")
    //@Pointcut("this(com.balfish.spring.aop.pointcutexp.Intf)")
    //@Pointcut("target(com.balfish.spring.aop.pointcutexp.Intf)")
    //@Pointcut("@within(org.springframework.transaction.annotation.Transactional)")
    //@Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
    @Pointcut("args(String)")
    public void pointcut() {
    }
    @Before(value = "pointcut()")
    public void beforeAdvice() {
        System.out.println("pointcut1 @Before...");
    }