基于XML配置方式的AOP
实现步骤
第一步: 定义目标类VipService
package com.powernode.spring6.service;
// 目标类
public class VipService {
public void add(){// 目标方法
System.out.println("保存vip信息。");
}
}
第二步: 定义切面类TimerAspect
负责计时,在切面类编写通知方法即我们要对目标对象增强的代码
public class TimerAspect {
public void time(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 前环绕
long begin = System.currentTimeMillis();
// 执行目标方法
proceedingJoinPoint.proceed();
// 后环绕
long end = System.currentTimeMillis();
System.out.println("耗时"+(end - begin)+"毫秒");
}
}
第三步 :在spring配置文件
使用标签进行配置,需要引入context和aop
的命名空间和约束文件
- 第一步: 首先将
目标类和切面类
注册为组件纳入Spring容器中管理 - 第二步: 使用
aop:aspect标签的ref属性
告诉Spring容器中的哪个类是切面类
- 第三步: 使用
aop:pointcut标签的expression属性
声明切点表达式,每个切点表达式都有一个id
属性便与通知引用 - 第四步: 使用
aop:around标签
声明一个环绕通知,method
属性指定切面类的通知方法,pointcut-ref
属性指定切点表达式即通知作用哪个目标对象的目标方法
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--将目标类和切面类纳入Spring管理-->
<bean id="vipService" class="com.powernode.spring6.service.VipService"/>
<bean id="timerAspect" class="com.powernode.spring6.service.TimerAspect"/>
<!--aop配置-->
<aop:config>
<!--通用的切点表达式-->
<aop:pointcut id="mypointcut" expression="execution(* com.powernode.spring6.service.VipService.*(..))"/>
<!--切面类=通知 + 切点-->
<aop:aspect ref="timerAspect">
<!--环绕通知-->
<aop:around method="time" pointcut-ref="mypointcut"/>
</aop:aspect>
</aop:config>
</beans>
第四步: 执行目标对象的目标方法,测试切面类中的通知方法
的执行顺序
public class AOPTest3 {
@Test
public void testAOPXml(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aop-xml.xml");
VipService vipService = applicationContext.getBean("vipService", VipService.class);
vipService.add();
}
}
保存vip信息
耗时4毫秒