1.声明schema,导入命名空间
(1)如果我们想要使用基于xml的spring aop,那么,第一步,我们需要在xml配置文件中声明spring aop schema,导入命名空间,如下这是一个标准的模板
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- //... -->
</beans>
(2)在xml配置文件中,所有的切面以及通知等都必须放置于<aop:config>标签内
2.声明一个切面
//定义一个切面类Logger,在其中声明一个前置通知
public class Logger {
public void beforePrint() {
System.out.println("before...");
}
}
<!-- xml配置文件 -->
<beans ....>
<!-- 将切面类注册为spring的一个bean -->
<bean id="logger" class="cn.example.spring.boke.Logger"></bean>
<aop:config>
<!-- 使用<aop:aspect>标签,来定义一个切面,其中id的值需唯一,ref用来引用切面类 -->
<aop:aspect id="aspect" ref="logger">
<!-- 在<aop:aspect>标签内部,我们可以定义5种通知,在这里使用<aop:before>标签来定义一个前置通知,其中method指定通知方法,它只能是Logger这个切面类中的方法,pointcut指定切入点表达式 -->
<aop:before method="beforePrint" pointcut="execution(* cn.example.spring.boke.ExampleA.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
3.声明一个切入点
<beans ....>
<bean id="logger" class="cn.example.spring.boke.Logger"></bean>
<aop:config>
<!-- 使用<aop:pointcut>标签来定义一个切入点,其中id的值唯一,expression即为切入点表达式 -->
<!-- 之后,在通知标签内部,使用pointcut-ref来引用这个切入点 -->
<aop:pointcut id="common" expression="execution(* cn.example.spring.boke.ExampleA.*(..))"/>
<!-- 在基于xml的切入点表达式中 &&, || 以及 ! 分别被替换为了 and, or 与 not,如下面这个例子 -->
<aop:pointcut id="mix" expression="execution(public * *(..)) and @args(org.springframework.stereotype.Component)"/>
<aop:aspect id="aspect" ref="logger">
<aop:before method="beforePrint" pointcut-ref="common"></aop:before>
</aop:aspect>
</aop:config>
</beans>
4.声明一个通知
//切面类
public class Logger {
public void beforePrint() {
System.out.println("before...");
}
public void afterReturningPrint(Object returnVal) {
System.out.println(returnVal);
System.out.println("afterReturning...");
}
public void afterThrowingPrint(Throwable throwable) {
System.out.println(throwable);
System.out.println("afterThrowing...");
}
public void afterPrint() {
System.out.println("after...");
}
public void aroundPrint(ProceedingJoinPoint joinPoint) {
try {
System.out.println("before...");
joinPoint.proceed();
System.out.println("after...");
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
System.out.println("finally...");
}
}
}
<aop