Spring学习
Maven依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1</version>
</dependency>
Spring 的环绕通知和前置通知,后置通知有着很大的区别,主要有两个重要的区别:1) 目标方法的调用由环绕通知决定,即你可以决定是否调用目标方法,而前置和后置通知是不能决定的,他们只是在方法的调用前后执行通知而已,即目标方法肯定是要执行的。2)环绕通知可以控制返回对象,即你可以返回一个与目标对象完全不同的返回值,虽然这很危险,但是你却可以办到。而后置方法是无法办到的,因为他是在目标方法返回值后调用。
Spring 提供了Interceptor 接口来实现环绕通知。它只有一个invoke 方法,该方法接只接受MethodInvocation 参数。MethodInvocation 可以获得目标方法的参数,并可以通过proceed 方法调用原来的方法。
● < aop:pointcut>:用来定义切入点,该切入点可以重用;
● < aop:advisor>:用来定义只有一个通知和一个切入点的切面;
● < aop:aspect>:用来定义切面,该切面可以包含多个切入点和通知,而且标签内部的通知和切入点定义是无序的;和advisor的区别就在此,advisor只包含一个通知和一个切入点。
Advisor(增强)和事务配合使用:使用环绕通知,实现访问次数控制的例子
<bean id="print" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean = "printtarget"></ref>
</property>
<property name="proxyInterfaces">
<value>com.bingone.Print</value>
</property>
<property name="interceptorNames">
<list> <value>writeLog</value> </list>
</property>
</bean>
<aop:config>
<aop:aspect id="writelogAOP" ref="writelog">
<aop:pointcut expression="execution(* com.bingone.*.*(..)) and args(..)"
id="moocPiontcut"/>
<aop:after method="after" pointcut-ref="moocPiontcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="moocPiontcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="moocPiontcut"/>
<aop:after method="after" pointcut-ref="moocPiontcut"/>
<aop:around method="around" pointcut-ref="moocPiontcut"/>
<aop:around method="aroundInit" pointcut="execution(* com.imooc.aop.schema.advice.biz.AspectBiz.init(String, int)) and args(bizName, times)"/>
<aop:declare-parents types-matching="com.imooc.aop.schema.advice.biz.*(+)"
implement-interface="com.imooc.aop.schema.advice.Fit" default-impl="com.imooc.aop.schema.advice.FitImpl" />
</aop:aspect>
</aop:config>