在使用springboot整合shiro的系统中,配置bean的时候往往要配置LifecycleBeanPostProcessor,一直没有深究这个的具体作用,只大概知道是用来管理shiro一些bean的生命周期。今天查了一下源码,总算揭开它的神秘面纱。
先来看看日常的配置:
@Bean("lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean @DependsOn({"lifecycleBeanPostProcessor"}) public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; }DefaultAdvisorAutoProxyCreator是用来扫描上下文,寻找所有的Advistor(通知器),将这些Advisor应用到所有符合切入点的Bean中。所以必须在lifecycleBeanPostProcessor创建之后创建,所以加
@DependsOn({"lifecycleBeanPostProcessor"})保证创建DefaultAdvisorAutoProxyCreator 之前先创建LifecycleBeanPostProcessor 。
再看看LifecycleBeanPostProcessor:
public class LifecycleBeanPostProcessor implements DestructionAwareBeanPostProcessor, PriorityOrdered { ......................... //省略。。。 public Object postProcessBeforeInitialization(Object object, String name) throws BeansException { if (object instanceof Initializable) { ((Initializable) object).init(); } return object; } public Object postProcessAfterInitialization(Object object, String name) throws BeansException { // Does nothing after initialization return object; } public void postProcessBeforeDestruction(Object object, String name) throws BeansException { if (object instanceof Destroyable) { ((Destroyable) object).destroy(); } } }点进源码发现这个类实现了DestructionAwareBeanPostProcessor,DestructionAwareBeanPostProcessor是什么?再深究,发现
这个已经是spring提供的了
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor { void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException; }BeanPostProcessor:
public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }再看看spring在初始化bean的时候:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { //省略。。。 Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } //省略。。。 invokeInitMethods(beanName, wrappedBean, mbd); //省略。。。 if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }其中applyBeanPostProcessorsBeforeInitialization和applyBeanPostProcessorsAfterInitialization就对应执行的是LifecycleBeanPostProcessor的postProcessBeforeInitialization和postProcessAfterInitialization,这里只举初始化的例子,销毁bean同理可得。
从此,可知道LifecycleBeanPostProcessor将Initializable和Destroyable的实现类统一在其内部自动分别调用了Initializable.init()和Destroyable.destroy()方法,从而达到管理shiro bean生命周期的目的。