InitializingBean of Spring core interface

1. Description of the
InitializingBean interface The InitializingBean interface provides the bean with a processing method after property initialization. It only includes the afterPropertiesSet method. All classes that inherit this interface will execute this method after the bean's properties are initialized.

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;

}

From the method name afterPropertiesSet, it can also be clearly understood that the method is called after the property is set.

2. Application of source code analysis interface
By looking at the source code class of spring loaded bean (AbstractAutowireCapableBeanFactory), you can see
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//Determine whether the bean implements the InitializingBean interface , if the InitializingBean interface is implemented, call the afterPropertiesSet method of the bean
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) { //Determine whether the init-method method is specified, if the init-method method is specified, then call the specified init-method
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//Reflect the init-method method
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
Analyze the code to understand:
1 : spring provides two ways to initialize beans for beans, implement the InitializingBean interface, implement the afterPropertiesSet method, or specify it with the init-method in the configuration file. Both methods can be used at the same time.
2: To implement the InitializingBean interface is to directly call the afterPropertiesSet method. It is relatively more efficient than calling the method specified by init-method through reflection. But the init-method method eliminates the dependency on spring
3: If there is an error when calling the afterPropertiesSet method, the method specified by the init-method is not called.

3. Interface application
  The InitializingBean interface has many applications in the spring framework itself, so I won't say much. How do we use this interface in practical applications?

1. Use the InitializingBean interface to process a configuration file:
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.springframework.beans.factory.InitializingBean;

public class ConfigBean implements InitializingBean{

// WeChat public account configuration file
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. Test
     public static void main(String[] args) throws Exception {
        String config = Test.class.getPackage().getName().replace('.', '/') + "/bean.xml";
           ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
           context.start();
        }


跟多技术文章


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326438874&siteId=291194637