怎么用spring Aop最简单最容易理解
1.先看一个例子
<aop:config> <aop:pointcut id="deleteOpus" expression="execution(* net.qdedu.activity.service.OpusBizService.delOpus(..))"/> <aop:aspect ref="activityParticipationAop"> <aop:after-returning method="deleteParticipationInfo" pointcut-ref="deleteOpus" returning="result"/> </aop:aspect> </aop:config>
aop:pointcut 指的是切入点 切入点的id是 deleteOpus
expression 指的是扫描对应的service类中的方法(delOpus),*代表的任意类型
aop:aspect ref 指的是对应方法类(activityParticipationAop)
aop:after-returning method 指的是你自己在(activityParticipationAop)里面创建的对应方法(deleteParticipationInfo)
ref 指的是 和切入点id 保持一致 id对应的是切点,ref就相当于是切面,他两个一相关联就可以执行那个service下面的方法了
2.对应的类
@Component public class ActivityParticipationAop { }
3.对应的方法
public void deleteParticipationInfo(JoinPoint jp){
//获取作品的id
IdParam idParam =(IdParam)jp.getArgs()[0];
}
JoinPoint是和aop一起使用的类,它里面有4个参数
Signature getSignature(); 获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息 Object[] getArgs(); 获取传入目标方法的参数对象 Object getTarget(); 获取被代理的对象 Object getThis(); 获取代理对象
4.增加切入点bean
<bean id="paramValidate" class="com.we.core.web.aop.ParamValidate"></bean> <aop:config> <aop:pointcut id="businessMethod" expression="execution(* *..*.service..*.*(..))"/> <aop:aspect ref="paramValidate"> <aop:before method="process" pointcut-ref="businessMethod"/> </aop:aspect> </aop:config>
5.springcontext.xml
<!-- 打开aop 注解 --> <aop:aspectj-autoproxy /> <!-- 扫描aop.xml --> <import resource="aop.xml" />