五、基于配置的AOP
(AOP.xml)
1、基于注解的AOP步骤
1、将目标类和切面类都加到IOC容器中:@Component
2、告诉Spring哪个类是切面类:在切面类上加@Aspect注解Spring就能认识
3、在切面类中使用五个注解来告诉Spring这个切面方法在何时何地执行
4、开启基于AOP注解的AOP功能:在xml中使用aop名称空间开启
<!--开启基于注解的AOP功能:aop名称空间-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
2、xml配置AOP的实验
1、复制一个SpringAOP项目,将两个切面类里面的所有注解全部删除,现在用xml文件进行配置,不用注解
2、Xml源码:
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!--基于配置的AOP-->
<bean id= "myCalculator" class="com.fxp.impl.MyCalculator"></bean>
<bean id="logUtils" class="com.fxp.util.LogUtils"></bean>
<bean id="validateAspect" class="com.fxp.util.ValidateAspect"></bean>
<!--需要AOP名称空间-->
<aop:config>
<!--指定哪个类是切面类-->
<aop:aspect ref="logUtils">
<!--在切面类中,配置5个通知方法告诉Spring这些切面方法在何时何地运行-->
<!--这个相当于抽取的可重用的切入点表达式,后面的只需要引用即可-->
<aop:pointcut id="pointcut" expression="execution(public * com.fxp.impl.*.*(..))"/>
<!--配置前置通知,直接写配置,不用引用-->
<aop:before method="logStart" pointcut="execution(public * com.fxp.impl.*.*(..))"></aop:before>
<!--配置后置通知,用外部引用-->
<aop:after method="LogEnd" pointcut-ref="pointcut"></aop:after>
<aop:after-returning method="LogReturn" pointcut-ref="pointcut" returning="result"></aop:after-returning>
<aop:after-throwing method="LogErr" pointcut-ref="pointcut" throwing="e"></aop:after-throwing>
<!--配置环绕通知-->
<aop:around method="myAround" pointcut-ref="pointcut"></aop:around>
</aop:aspect>
<!--第二个切面类-->
<aop:aspect ref="validateAspect">
<!--这里的切入点表达式也可以直接引用上面那个aop标签里面的,虽然他们不在同一个aop标签,但是一样可以引用-->
<aop:before method="logStart" pointcut-ref="pointcut"></aop:before>
<aop:after method="LogEnd" pointcut-ref="pointcut"></aop:after>
<aop:after-returning method="LogReturn" pointcut-ref="pointcut" returning="result"></aop:after-returning>
<aop:after-throwing method="LogErr" pointcut-ref="pointcut" throwing="e"></aop:after-throwing>
</aop:aspect>
</aop:config>
3、运行结果:
4、这里的先后顺序,是看在xml配置文件里,谁配置在前面,就谁先执行。
3、注解和配置的优缺点
注解:方便快速,但是如果有一个切面类是外部jar引用进来的,就无法用注解加入到目标类里面
配置:功能完善,不管是自己写的切面类还是外部引用的,都可以加入到目标类里面。