springframework【8】
Spring的Advices
Advices实现了Aspect的真正逻辑。由于织入至Targets的实际不同,spring提供了不同的Advices,像Before Advice,After Advice,Around Advice,Throw Advice。
(1)、Before Advice
通过实现MethodBeforeAdvice来定义
(2)、After Advice
通过实现AfterReturningAdvice来定义
(3)、Around Advice
通过实现MethodInterceptor来定义
(4)、Throw Advice
通过实现ThrowsAdvice来定义
我们将使用一个代理的bean aaa,给这个代理的bean加上我们spring的advice,看看他的日志输出表现。我们通过代码示例来说明:
1、定义基本的advice Bean以及要被调用的类
(1)、beforeAdvice的Bean
?
?
3、在main函数中调用
package com.itcast.advice;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.itcast.proxy.IHello;public class AdviceMain {/**对于给基本的spring bean强行指定一批advice方法的调用展示**/public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-config.xml");IHello h = (IHello)ctx.getBean("aaa");h.hiAAA("测试配置aop的adivce");System.out.println("进行抛出异常的adivce展示-==================");try {h.hiBBB("测试抛出异常的advice");} catch (Exception e) {}}}?
4、控制台的显示
around 调用方法之前....
beforeAdvice 调用方法之前被执行!...........
我在HelloSpeaker1中---hiAAA[测试配置aop的adivce]
afterAdvice 调用方法之后被执行!...........
around 调用方法之后...
进行抛出异常的adivce展示-==================
15:05:05,671 DEBUG ThrowsAdviceInterceptor:88 - Found exception handler method: public void com.itcast.advice.ThrowAdvice.afterThrowing(java.lang.reflect.Method,java.lang.Object[],java.lang.Object,java.lang.Throwable)
around 调用方法之前....
beforeAdvice 调用方法之前被执行!...........
我在HelloSpeaker1中---hiBBB[测试抛出异常的advice]
15:05:05,687 DEBUG ThrowsAdviceInterceptor:119 - Found handler for exception of type [java.lang.Throwable]: public void com.itcast.advice.ThrowAdvice.afterThrowing(java.lang.reflect.Method,java.lang.Object[],java.lang.Object,java.lang.Throwable)
ThrowAdvice 记录异常...........?
?