().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->后置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}
12.4.1.2、配置后置通知到切面
<!--
aop:after标签:将方法设置为该切面的后置通知(方法),效果等同于@After注解
-->
<aop:after method="afterMethod" pointcut-ref="pointcutOne"></aop:after>
12.4.1.3、测试使用效果
由控制台日志可知,后置通知在目标对象方法的finally子句中执行(一般用于释放资源)
@Test
public void testAOPByXML(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aopByxml.xml");
// 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class);
// 只能通过代理对象来访问目标对象中的方法
calculator.div(1,0);
}
12.4.2、返回通知
12.4.2.1、定义返回通知的功能
public void afterReturningMethod(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->返回通知,方法名:"+methodName+",结果:"+ result);
}
12.4.2.2、配置返回通知到切面
<!--
aop:after-returning标签:将方法设置为该切面的返回通知(方法),效果等同于@AfterReturning注解
returning属性:指定返回通知(方法)中的某个参数(名),用于接收目标对象方法的返回值
-->
<aop:after-returning method="afterReturningMethod" pointcut-ref="pointcutOne" returning="result"></aop:after-returning>
12.4.2.3、测试使用效果
返回通知在目标对象方法的返回值之后执行
@Test
public void testAOPByXML(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aopByxml.xml");
// 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class);
// 只能通过代理对象来访问目标对象中的方法
calculator.div(1,1);
}
12.4.3、异常通知
12.4.3.1、定义异常通知的功能
public void afterThrowingMethod(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->异常通知,方法名:"+methodName+",异常:"+ ex);
}
12.4.3.2、配置异常通知到切面
<!--
aop:after-throwing标签:将方法设置为该切面的异常通知(方法),效果等同于@AfterThrowing注解
throwing属性:指定异常通知(方法)中的某个参数(名),用于接收目标对象方法出现的异常
-->
<aop:after-throwing method="afterThrowingMethod" pointcut-ref="pointcutOne" throwing="ex" ></aop:after-throwing>
12.4.3.3、测试使用效果
由控制台日志可知,异常通知在目标对象方法的catch子句中执行
@Test
public void testAOPByXML(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aopByxml.xml");
// 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class);
// 只能通过代理对象来访问目标对象中的方法
calculator.div(1,0);
}
12.5、环绕通知
12.5.1、定义环绕通知的功能
环绕通知和动态代理的形式,非常相似
/**
* 环绕通知(方法)使用的参数是ProceedingJoinPoint类型
* 环绕通知(方法)的返回值,必须和目标对象方法的返回值一致
*/
public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){
String methodName = proceedingJoinPoint.getSignature().getName();
Object[] args = proceedingJoinPoint.getArgs();
Object result = null;
try {
System.out.println("LoggerAspect-->环绕前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
// 表示目标对象方法的执行
result = proceedingJoinPoint.proceed();
System.out.println("Log