Spring AOP在Bean生命周期中的调用时机

来源:互联网 发布:变革管理 知乎 编辑:程序博客网 时间:2024/06/07 03:16

之前有写了一个生命周期的例子,直接拿来用,在每个生命周期方法中调用print方法。见上一篇


加上AOP的代码


package com.aspect;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;@Aspect@Componentpublic class AroundAspect {@Around("execution(* com.bean.MyMode.*(..))")public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {String methodName = pjp.getSignature().getName();System.out.println("----Aspect before " + methodName + " called ");Object retVal = pjp.proceed();System.out.println("----Aspect after " + methodName + " called ");return retVal;}}


运行得到结果:


InstantiationBeanPostProcessor postProcessBeforeInstantiation called


MyMode constructor call
1
MyMode constructor finish


InstantiationBeanPostProcessor postProcessAfterInstantiation called


InstantiationBeanPostProcessor postProcessPropertyValues called


BeanPostProcessor postProcessBeforeInitialization called
1
BeanPostProcessor postProcessBeforeInitialization finish


Mode @PostConstruct anno init called
1
MyMode @PostConstruct anno init finish


Mode afterPropertiesSet called
1
MyMode afterPropertiesSet finish


Mode @Bean anno Init called
1
MyMode @Bean anno Initfinish


BeanPostProcessor postProcessAfterInitialization called
----Aspect before print called 
1
----Aspect after print called 
BeanPostProcessor postProcessAfterInitialization finish


----Aspect before print called 
1
----Aspect after print called 


Mode @PreDestroy anno destory called
1
MyMode @PostConstruct anno destory finish


Mode destroy called
1
MyMode destroy finish


Mode @Bean anno destory called
1
MyMode @Bean anno destory finish



结论是:在Bean的整个生命周期中,只有在初始化方法调用完之后销毁之前,AOP是有效的。

0 0
原创粉丝点击