第六节 基于XML的AOP[了解]
1、准备工作
①加入依赖
和基于注解的AOP时一样。
②准备代码
把测试基于注解功能时的Java类复制到新module中,去除所有注解。
2、配置Spring配置文件
<!-- 配置切入点表达式 --><br /> <aop:pointcut id="logPointCut" expression="execution(* *..*.*(..))"/>
<!-- aop:aspect标签:配置切面 --><br /> <!-- ref属性:关联切面类的bean --><br /> <aop:aspect ref="logAspect"><br /> <!-- aop:before标签:配置前置通知 --><br /> <!-- method属性:指定前置通知的方法名 --><br /> <!-- pointcut-ref属性:引用切入点表达式 --><br /> <aop:before method="printLogBeforeCore" pointcut-ref="logPointCut"/>
<!-- aop:after-returning标签:配置返回通知 --><br /> <!-- returning属性:指定通知方法中用来接收目标方法返回值的参数名 --><br /> <aop:after-returning<br /> method="printLogAfterCoreSuccess"<br /> pointcut-ref="logPointCut"<br /> returning="targetMethodReturnValue"/>
<!-- aop:after-throwing标签:配置异常通知 --><br /> <!-- throwing属性:指定通知方法中用来接收目标方法抛出异常的异常对象的参数名 --><br /> <aop:after-throwing<br /> method="printLogAfterCoreException"<br /> pointcut-ref="logPointCut"<br /> throwing="targetMethodException"/>
<!-- aop:after标签:配置后置通知 --><br /> <aop:after method="printLogCoreFinallyEnd" pointcut-ref="logPointCut"/>
<!-- aop:around标签:配置环绕通知 --><br /> <!--<aop:around method="……" pointcut-ref="logPointCut"/>--><br /> </aop:aspect>
3、测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {“classpath:spring-context.xml”})
public class AOPTest {
@Autowired<br /> private Calculator calculator;
@Test<br /> public void testLogAspect() {<br /> int add = calculator.add(10, 2);<br /> System.out.println("add = " + add);<br /> }<br />}