1. 程式人生 > 其它 >Spring中的InitializingBean介面的使用[轉]

Spring中的InitializingBean介面的使用[轉]

轉自:https://www.cnblogs.com/weiqihome/p/8922937.html

InitializingBean介面為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該介面的類,在初始化bean的時候都會執行該方法。

測試,如下:

import org.springframework.beans.factory.InitializingBean;
public class TestInitializingBean implements InitializingBean{
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("ceshi InitializingBean");        
    }
    public void testInit(){
        System.out.println("ceshi init-method");        
    }
}

配置檔案

<bean id="testInitializingBean" class="com.TestInitializingBean" ></bean>

Main函式如下

public class Main {
    public static void main(String[] args){
        ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/java/com/beans.xml");
    }
}

測試結果為:

ceshi InitializingBean

這說明在spring初始化bean的時候,如果bean實現了InitializingBean介面,會自動呼叫afterPropertiesSet方法。

那麼問題來了,在配置bean的時候使用init-method配置也可以為bean配置初始化方法,那這兩個哪個會先執行呢,接下來測試一下,修改配置檔案,加上init-method:

<bean id="testInitializingBean" class="com.TestInitializingBean" init-method="testInit"></bean>

執行程式,得出結果:

ceshi InitializingBean
ceshi init-method

從結果可以看出,在Spring初始化bean的時候,如果該bean實現了InitializingBean介面,並且同時在配置檔案中指定了init-method,系統則是先呼叫afterPropertieSet()方法,然後再呼叫init-method中指定的方法。

那麼這種方式在spring中是怎麼實現的呢,通過檢視Spring載入bean的原始碼類AbstractAutowiredCapableBeanFactory可以看出其中的奧妙,AbstractAutowiredCapableBeanFactory類中的invokeInitMethods說的非常清楚,如下:

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
    //判斷該bean是否實現了實現了InitializingBean介面,如果實現了InitializingBean介面,則只掉呼叫bean的afterPropertiesSet方法
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
         
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    public Object run() throws Exception {
                        //直接呼叫afterPropertiesSet
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }
                },getAccessControlContext());
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }                
        else {
            //直接呼叫afterPropertiesSet
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }
    if (mbd != null) {
        String initMethodName = mbd.getInitMethodName();
        //判斷是否指定了init-method方法,如果指定了init-method方法,則再呼叫制定的init-method
        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            //進一步檢視該方法的原始碼,可以發現init-method方法中指定的方法是通過反射實現
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

總結:

1、Spring為bean提供了兩種初始化bean的方式,實現InitializingBean介面,實現afterPropertiesSet方法,或者在配置檔案中通過init-method指定,兩種方式可以同時使用。

2、實現InitializingBean介面是直接呼叫afterPropertiesSet方法,比通過反射呼叫init-method指定的方法效率要高一點,但是init-method方式消除了對spring的依賴。

3、如果呼叫afterPropertiesSet方法時出錯,則不呼叫init-method指定的方法。