Spring_AOP_XML使用Aspect实现动态代理(常用)
XML使用Aspect实现动态代理此方式比较常用,和使用注解最大的好处是我们不用每个方法前面定义横切点上面加入PointCut的说明,在XML中只需要定义一次就可以多出使用。
在上面Spring_AOP_Annotation使用Aspect实现动态代理的基础上修改,去除LogAspect中方法上的注解。
XML文件配置:
<?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/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
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-3.2.xsd">
<!-- 打开Spring的Annotation的支持 -->
<context:annotation-config />
<!-- 设定Spring去哪些包中找Annotation -->
<context:component-scan base-package="com.spring" />
<!-- 打开基于Annotation的aop自动代理 -->
<aop:aspectj-autoproxy />
<aop:config>
<!-- 定义切面 -->
<aop:aspect id="myLogAspect" ref="logAspect">
<!-- 在哪些位置加入相应的Aspect -->
<aop:pointcut id="logPointCut"
expression="execution(* com.spring.dao.*.add*(..))||
execution(* com.spring.dao.*.update*(..))||
execution(* com.spring.dao.*.delete*(..))" />
<!-- 开始之前加入日志 -->
<aop:before method="logStart" pointcut-ref="logPointCut" />
<!-- 结束之后加入日志 -->
<aop:after method="logEnd" pointcut-ref="logPointCut" />
<!-- 执行过程中加入日志 -->
<aop:around method="logAround" pointcut-ref="logPointCut"/>
</aop:aspect>
</aop:config>
</beans>
LogAspect类:
package com.spring.proxy;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
//让这个切面类被Spring所管理
@Component("logAspect")
// 声明这是一个切面类
@Aspect
public class LogAspect {
public void logStart(JoinPoint jp) {
// 得到执行的对象
System.out.println(jp.getTarget());
// 得到执行的方法
System.out.println(jp.getSignature().getName());
Logger.info("方法执行前加入日志,来自LogAspect");
}
public void logEnd(JoinPoint jp) {
// 得到执行的对象
System.out.println(jp.getTarget());
// 得到执行的方法
System.out.println(jp.getSignature().getName());
Logger.info("方法执行后加入日志,来自LogAspect");
}
public void logAround(ProceedingJoinPoint pjp) throws Throwable {
Logger.info("开始在Around中加入日志,来自LogAspect");
//执行程序
pjp.proceed();
Logger.info("结束Around");
}
}
测试代码及测试结果: