紧接着(三)中的例子。其实Spring AOP注解的概念理解了后,看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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.bjsxt"/>
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<aop:pointcut expression="execution(public * com.bjsxt.service..*.add(..))" id="logPointCut"/>
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut-ref="logPointCut" />
</aop:aspect>
</aop:config>
</beans>
(1) 首先去掉了<aop:aspectj-autoproxy />这句
(2) 还是得先初始化一个LogInteceptor对象,所以要先写一个<bean>
(3) AOP的配置写在<aop:config></aop:config>内
(4) 调用add()方法时,Spring发现符合pointcut("logPointCut"),然后这个poincut又被aspect("logAspect")引用到了,所以就去执行相应的切面逻辑
(5) 上面定义了一个全局的pointcut("logPointCut"),这意味着其他的aspect都可以通过id引用这个pointcut。其实也可以将pointcut写在aspect内,这样相当于一个私有pointcut,其他的aspect无法引用这个pointcut(没有id):
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean> <aop:config> <aop:aspect id="logAspect" ref="logInterceptor"> <aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" /> </aop:aspect> </aop:config>
某些情况下,要使用别人的切面类(比如一个测量代码性能的工具,要把测量的逻辑织入你自己的代码),这时你不可能在别人的切面类代码上加注解,所以只有通过XML来配置。目前在实际使用中,XML的使用也是多于注解。
本文深入解析Spring AOP注解概念,并详细阐述如何通过XML配置实现AOP功能,包括点切面配置、切点表达式、前置通知等关键步骤。同时,对比注解与XML配置的使用场景,帮助开发者灵活选择合适的配置方式。
798

被折叠的 条评论
为什么被折叠?



