使用 XML 配置 Spring AOP的前置通知
1 准备工作
1.1 创建EmpService接口
package com.service;
public interface EmpService {
void add();
void find();
}
1.2 创建EmpService接口的实现类EmpServiceImpl
package com.service.impl;
import com.service.EmpService;
public class EmpServiceImpl implements EmpService {
@Override
public void add() {
System.out.println("添加员工");
}
@Override
public void find() {
System.out.println("查询员工");
}
}
1.3 注意:接口和实现类需要满足以下位置关系

1.4 导入AOP实现依赖
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.7version>
dependency>
2 创建切面类并通过Joinpoint 拿到目标对象 方法 参数
package com.aop;
import org.aspectj.lang.JoinPoint;
public class Aop {
public void a(JoinPoint jp){
System.out.println("记录日志: 执行了方法"+jp.getSignature().getName());
}
}
3 spring-config文件配置
3.1 创建组件
<bean id="aop" class="com.aop.Aop">bean>
<bean id="es" class="com.service.impl.EmpServiceImpl">bean>
3.2 输入aop:config然后回车
<aop:config>aop:config>
3.3 在aop:config里面进行切入点配置
3.1.1 代码
<aop:pointcut id="ppp" expression="execution(* com.service.impl.*.*(..))"/>
3.1.2 分析
目的:就是告知被切入的范围是什么
3.4 通知配置
3.4.1 代码
<aop:before method="a" pointcut-ref="ppp">aop:before>
3.4.2 分析
说白了就是告知啥时候切入(在调用方法之前,还是调用方法之后),
切入方法是什么
告知啥地方需要切入
a before就是前置通知
b method就是被切入的时候调用哪个方法
c pointcut-ref是切入点(哪些类需要被切入)
d 最外层的ref="aop"引入的哪个切面组件了
3.5 测试代码
import com.service.EmpService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");
EmpService es = ac.getBean(EmpService.class);
es.add();
System.out.println("------");
es.find();
}
}
3.6 测试代码运行截图
