Spring核心介面之InitializingBean

happyhuangjinjin發表於2017-12-17

一、InitializingBean介面說明
InitializingBean介面為bean提供了屬性初始化後的處理方法,它只包括afterPropertiesSet方法,凡是繼承該介面的類,在bean的屬性初始化後都會執行該方法。

package org.springframework.beans.factory;

/**
 * Interface to be implemented by beans that need to react once all their
 * properties have been set by a BeanFactory: for example, to perform custom
 * initialization, or merely to check that all mandatory properties have been set.
 *
 * <p>An alternative to implementing InitializingBean is specifying a custom
 * init-method, for example in an XML bean definition.
 * For a list of all bean lifecycle methods, see the BeanFactory javadocs.
 *
 * @author Rod Johnson
 * @see BeanNameAware
 * @see BeanFactoryAware
 * @see BeanFactory
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
 * @see org.springframework.context.ApplicationContextAware
 */
public interface InitializingBean {

    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     * @throws Exception in the event of misconfiguration (such
     * as failure to set an essential property) or if initialization fails.
     */
    void afterPropertiesSet() throws Exception;

}

從方法名afterPropertiesSet也可以清楚的理解該方法是在屬性設定後才呼叫的。
二、原始碼分析介面應用
通過檢視spring的載入bean的原始碼類(AbstractAutowireCapableBeanFactory)可以看到

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) {            //判斷是否指定了init-method方法,如果指定了init-method方法,則再呼叫制定的init-method
            String initMethodName = mbd.getInitMethodName();
            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指定的方法。

三、介面應用
InitializingBean介面在spring框架中本身就很多應用,這就不多說了。我們在實際應用中如何使用該介面呢?

1、使用InitializingBean介面處理一個配置檔案:

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.springframework.beans.factory.InitializingBean;

public class ConfigBean implements InitializingBean{
    
    //微信公眾號配置檔案
    private String configFile;
    
    private String appid;
    
    private String appsecret;
    
    public String getConfigFile() {
        return configFile;
    }

    public void setConfigFile(String configFile) {
        this.configFile = configFile;
    }
    
    public void afterPropertiesSet() throws Exception {
        if(configFile!=null){
            File cf = new File(configFile);
            if(cf.exists()){
                Properties pro = new Properties();
                pro.load(new FileInputStream(cf));
                appid = pro.getProperty("wechat.appid");
                appsecret = pro.getProperty("wechat.appsecret");
            }
        }
        System.out.println(appid);
        System.out.println(appsecret);
    }
}

2、配置
spring配置檔案:

    <bean id="configBean" class="com.ConfigBean">
        <property name="configFile" value="d:/wechat.properties"></property>
    </bean>

wechat.properties配置檔案

    wechat.appid=wxappid
    wechat.appsecret=wxappsecret

3、測試

 public static void main(String[] args) throws Exception {
        String config = Test.class.getPackage().getName().replace(`.`, `/`) + "/bean.xml";
       ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
       context.start();
    }



相關文章