在使用spring整合shiro的系统中,配置bean的时候往往要配置LifecycleBeanPostProcessor,一直没有深究这个的具体作用,只大概知道是用来管理shiro一些bean的生命周期。今天查了一下源码,总算揭开它的神秘面纱。
先来看看日常的配置:
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<bean id="annotationProxy"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
DefaultAdvisorAutoProxyCreator是用来扫描上下文,寻找所有的Advistor(通知器),将这些Advisor应用到所有符合切入点的Bean中。所以必须在lifecycleBeanPostProcessor创建之后创建,所以用了depends-on=”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是什么?再深究:
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生命周期的目的。