1. 程式人生 > >shiro學習之LifecycleBeanPostProcessor的作用

shiro學習之LifecycleBeanPostProcessor的作用

在使用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”>

再看看LifecycleBeanPostProce:

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生命週期的目的。