1、需要jar包
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.7.0.jar
aspectjweaver-1.7.0.jar
cglib-2.2.2.jar
2、xml配置
<?xml version="1.0" encoding="UTF-8"?><!-- 一般化的Spring XML 配置 -->
<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:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config/>
<bean id="loggerAspect" class="com.my.spring.aop.LogAspect"></bean>
<!-- 为接口类设置切点 -->
<aop:config>
<aop:aspect ref="loggerAspect">
<!-- 之前 -->
<aop:around pointcut="execution(* com.my.remotting.server.*.*(..))" method="log"/>
</aop:aspect>
</aop:config>
</beans>
3、aop类
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
public class LogAspect{
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("我在被监视程序之前。。。");
/* Object[] args = joinPoint.getArgs();
Object object = joinPoint.proceed(args);*/
Object object = joinPoint.proceed();
System.out.println("我在被监视程序之后。。。" );
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
System.out.println("methodName="+methodName);
return object;
}
}
本文详细介绍如何在Spring框架中使用AOP(面向切面编程),包括所需jar包、XML配置及AOP类实现。通过具体代码示例,展示了如何定义切点、引入AspectJ并创建环绕通知,以实现在方法调用前后进行日志记录。

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



