一.前置知识
消息分类:
before :前置消息,即在目标方法执行之前执行。
after-returning:后置消息,即在目标方法执行之后执行。
after-throwing:异常消息,即在目标方法中执行到出现异常后执行。
after :最终消息,此方法无论是否异常都会最终执行。
原理:spring aop是使用动态代理(包括基于接口和基于子类两种代理)spring会根据情况选择相应的类型。动态代理内部使用的反射进行获取对象并执行方法。
问题:在配置aop时,将aop:after和aop:after-returning位置互换,那么在目标方法上执行效果也是两者互换。
<aop:config>
<aop:aspect id="useAspect" ref="useAdvice">
<aop:pointcut id="usePointcut" expression="execution(public void com.xzx.Service.Impl.ServiceImpl.show2(int))"></aop:pointcut>
<aop:before method="before" pointcut-ref="usePointcut"></aop:before>
<aop:after-returning method="afterreturning" pointcut-ref="usePointcut"></aop:after-returning>
<aop:after method="after" pointcut-ref="usePointcut"></aop:after>
<aop:after-throwing method="afterthrowing" pointcut-ref="usePointcut"></aop:after-throwing>
</aop:aspect>
</aop:config>
消息类,作为消息织入到切点,形成切面
package com.xzx.Advice;
/**
* @Auther Oonday
* @Date 2021-07-27 11:20
*/
public class useAdvice {
public void before(){
System.out.println("前置日志before通知执行。。。。。。");
}
public void afterreturning(){
System.out.println("后置日志afterreturning通知执行。。。。。。");
}
public void afterthrowing(){
System.out.println("异常日志afterthrowing通知执行。。。。。。");
}
public void after(){
System.out.println("最终日志after通知执行。。。。。。");
}
}
Srvice服务类
package com.xzx.Service.Impl;
import com.xzx.Service.UseService;
/**
* @Auther Oonday
* @Date 2021-07-27 11:13
*/
public class ServiceImpl implements UseService {
public void show() {
System.out.println("show方法执行0000000000000");
}
public int show1() {
System.out.println("show1方法执行11111111111");
return 0;
}
public void show2(int id) {
// int i=1/0;
System.out.println("show2方法执行"+id);
// int i=1/0;
}
}
测试类
package com.xzx.TestAop;
import com.xzx.Service.Impl.ServiceImpl;
import com.xzx.Service.UseService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Auther Oonday
* @Date 2021-07-27 11:26
*/
public class UseAop {
@Test
public void Test01(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UseService serviceImpl = applicationContext.getBean("ServiceImpl", UseService.class);
serviceImpl.show2(6);
}
}
测试结果:
前置日志before通知执行。。。。。。
show2方法执行6
后置日志afterreturning通知执行。。。。。。
最终日志after通知执行。。。。。。
更改两者位置后:
<aop:config>
<aop:aspect id="useAspect" ref="useAdvice">
<aop:pointcut id="usePointcut" expression="execution(public void com.xzx.Service.Impl.ServiceImpl.show2(int))"></aop:pointcut>
<aop:before method="before" pointcut-ref="usePointcut"></aop:before>
<aop:after-throwing method="afterthrowing" pointcut-ref="usePointcut"></aop:after-throwing>
<aop:after method="after" pointcut-ref="usePointcut"></aop:after>
<aop:after-returning method="afterreturning" pointcut-ref="usePointcut"></aop:after-returning>
</aop:aspect>
</aop:config>
前置日志before通知执行。。。。。。
show2方法执行6
最终日志after通知执行。。。。。。
后置日志afterreturning通知执行。。。。。。
服务类方法1/0的错误后,才会执行异常方法啦,各位自行测试