- 方式1:使用Spring的API接口,就是我们使用BeforeLog和AfterLog实现的那两个接口,就是Spring的API接口【通过实现spring的API】
- 方式2:自定义实现AOP【通过定义一个切面类实现】
1.代码实现
相同的需求,使用方法2实现
- 定义一个切面类
- 配置spring容器
<?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"> <!--注册bean--> <bean id="userServiceImpl" class="com.thhh.service.UserServiceImpl"/> <bean id="beforeLog" class="com.thhh.Log.BeforeLog"/> <bean id="afterLog" class="com.thhh.Log.AfterLog"/> <!-- <!–配置AOP–> <!–1、导入AOP约束–> <aop:config> <!–2、设置pointcut切入点,这里就是在配置代理模式中前戏、核心方法、收尾工作的执行顺序–> <!– expression表达式,这是固定的格式,即expression="execution(要执行的位置)" execution()里填写的就是执行的位置,里面填写的格式为:*(修饰符) *(返回值) *(类名) *(方法名) *(参数),*代表通配 –> <aop:pointcut id="pointcut" expression="execution(* com.thhh.service.UserServiceImpl.*(..) )"/> <!–执行环绕(advisor)增强,就是在执行上面指定的切入点的前后增加执行一个什么方法,就叫执行环绕增强,名字唬人–> <!–方法具体是执行核心方法前执行还是执行核心方法后执行,是由方法继承的接口决定的,所以我们在配置执行的方法的时候只需要指定哪个切入点引用哪个 bean/对象 即可–> <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config>--> <!--自定义切面实现AOP--> <bean id="aspect" class="com.thhh.aspect.aspect"/> <aop:config> <!--自定义一个切面,切面需要指定要引用哪个切面类,指定了引用哪个切面类,我们才能指定在什么时候执行这个切面类中的什么方法--> <aop:aspect id="aspect" ref="aspect"> <!--定义这个切面的切入点--> <aop:pointcut id="pointcut" expression="execution(* com.thhh.service.UserServiceImpl.*(..) )"/> <!--通知增强--> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>
2.对比
-
方法1中控制方法 执行的时机/增强通知 的是spring的接口api
-
方法2中控制方法 执行的时机/增强通知 的是aop自己,通过aop:before/after控制
-
方法1直接在aop:config节点中定义了一个切入点aop:pointcut,然后定义了两个环绕通知aop:advisor
-
方法2在中定义了一个切面aop:aspect,切入点aop:pointcut随便定义在切面里或者切面外,它和切面是否定义无关,切面的环绕通知aop:before和aop:after必须定义在切面节点aop:aspect里面