SpringコアインタフェースのInitializingBean


一、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.
 *
 * 

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). *

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のソースクラス(A b s t r a c t o u t w i r e CapableBeanFactory)を表示すると、protected void invokeInitMethods(String beanName,final Object bean,RootBeanDefinitionmbd)throws Throwable{//このbeanがInitializingBeanインタフェースを実装したかどうかを判断し、InitializingBeanインタフェースを実装した場合、beanのafterPropertiesSetメソッドboolean isInitializingBean=(bean instanceof InitializingBean);if(isInitializingBean&(mbd==null|!mbd.isExternalymanagedInitMethod("afterPropertiesSet")))){if(logger.isDebugEnabled())を呼び出す.{logger.debug("Invoking afterPropertiesSet() on bean with name '"+ beanName + "'");}if (System.getSecurityManager() != null){try{AccessController.doPrivileged(new PrivilegedExceptionAction){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に2つの初期化beanを提供し、InitializingBeanインタフェースを実現し、afterPropertiesSetメソッドを実現したり、プロファイルでinit-methodと指定したりすることができます.2つの方法は同時に使用できます.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プロファイルの設定:wechat.propertiesプロファイルwechat.appid=wxappidwechat.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();