一咨演、InitializingBean接口說(shuō)明
InitializingBean接口為bean提供了屬性初始化后的處理方法咳蔚,它只包括afterPropertiesSet方法避矢,凡是繼承該接口的類寡润,在bean的屬性初始化后都會(huì)執(zhí)行該方法祖驱。
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也可以清楚的理解該方法是在屬性設(shè)置后才調(diào)用的停士。
二挖帘、源碼分析接口應(yīng)用
通過查看spring的加載bean的源碼類(AbstractAutowireCapableBeanFactory)可以看到
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//判斷該bean是否實(shí)現(xiàn)了實(shí)現(xiàn)了InitializingBean接口,如果實(shí)現(xiàn)了InitializingBean接口向瓷,則調(diào)用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() {
public Object run() throws Exception {
//調(diào)用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//調(diào)用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {//判斷是否指定了init-method方法肠套,如果指定了init-method方法,則再調(diào)用制定的init-method
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//反射調(diào)用init-method方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
分析代碼可以了解:
1:spring為bean提供了兩種初始化bean的方式猖任,實(shí)現(xiàn)InitializingBean接口你稚,實(shí)現(xiàn)afterPropertiesSet方法,或者在配置文件中同過init-method指定朱躺,兩種方式可以同時(shí)使用
2:實(shí)現(xiàn)InitializingBean接口是直接調(diào)用afterPropertiesSet方法刁赖,比通過反射調(diào)用init-method指定的方法效率相對(duì)來(lái)說(shuō)要高點(diǎn)。但是init-method方式消除了對(duì)spring的依賴
3:如果調(diào)用afterPropertiesSet方法時(shí)出錯(cuò)长搀,則不調(diào)用init-method指定的方法宇弛。
三、接口應(yīng)用
InitializingBean接口在spring框架中本身就很多應(yīng)用源请,這就不多說(shuō)了枪芒。我們?cè)趯?shí)際應(yīng)用中如何使用該接口呢彻况?
1、使用InitializingBean接口處理一個(gè)配置文件:
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.springframework.beans.factory.InitializingBean;
public class ConfigBean implements InitializingBean{
//微信公眾號(hào)配置文件
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=wxappid
wechat.appsecret=wxappsecret
3纽甘、測(cè)試
public static void main(String[] args) throws Exception {
String config = Test.class.getPackage().getName().replace('.', '/') + "/bean.xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
context.start();
}