feat(aop): 添加基于XML配置的AOP功能实现

- 创建bean-aop-xml.xml配置文件,定义Student Bean和AOP切面配置
- 实现Log通知类,提供前置通知功能用于日志记录
- 将Student类从di包移动到aop.xml包下进行重构
- 添加Test测试类,验证AOP切入点和前置通知的正确执行
- 配置AOP切点表达式,拦截com.ssm.aop.xml包下所有方法调用
- 实现完整的AOP XML配置方案,支持方法执行前的日志输出功能
main
CesarH 3 weeks ago
parent 8343420ba9
commit 4024266cb7

@ -0,0 +1,37 @@
<?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">
<!-- 1. 配置Student实体类Bean -->
<bean id="student" class="com.ssm.aop.xml.Student">
<!-- 给属性注入测试值 -->
<property name="studentId" value="2025001"/>
<property name="studentName" value="张三"/>
<property name="className" value="自动化2班"/>
<property name="major" value="自动化"/>
<property name="age" value="20"/>
<property name="phone" value="13800138000"/>
</bean>
<!-- 2. 配置前置通知类Log的Bean -->
<bean id="logAdvice" class="com.ssm.aop.xml.Log"/>
<!-- 3. AOP配置切入点 + 切面 + 前置通知 -->
<aop:config>
<!-- 定义切入点匹配com.ssm.aop.xml包下所有类的所有方法也可以指定printInfo -->
<aop:pointcut id="allMethods" expression="execution(* com.ssm.aop.xml.*.*(..))"/>
<!-- 定义切面:将通知类和切入点绑定 -->
<aop:aspect ref="logAdvice">
<!-- 前置通知在切入点方法执行前执行beforeAdvice方法 -->
<aop:before method="beforeAdvice" pointcut-ref="allMethods"/>
</aop:aspect>
</aop:config>
</beans>

@ -0,0 +1,14 @@
package com.ssm.aop.xml;
import org.aspectj.lang.JoinPoint; // 必须导入这个!
public class Log {
// 前置通知:在目标方法执行前执行
public void beforeAdvice(JoinPoint joinPoint) {
// 获取目标类名
String className = joinPoint.getTarget().getClass().getName();
// 获取目标方法名
String methodName = joinPoint.getSignature().getName();
System.out.println("前置通知:模拟日志记录...目标类是:" + className + ",被切入通知的目标方法为:" + methodName);
}
}

@ -1,4 +1,4 @@
package com.ssm.di;
package com.ssm.aop.xml;
public class Student {
// 学生核心属性

@ -0,0 +1,17 @@
package com.ssm.aop.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// 加载Spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean-aop-xml.xml");
// 获取Student的Bean实例
Student student = (Student) ac.getBean("student");
// 调用打印方法AOP会自动切入前置通知
student.printInfo();
}
}
Loading…
Cancel
Save