之前有写了一个生命周期的例子,直接拿来用,在每个生命周期方法中调用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
@Component
public 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是有效的。