InitializingBean
spring的InitializingBean為bean提供了定義初始化方法的方式。InitializingBean是一個接口,只包含一個方法:afterPropertiesSet():
throws Exception;
}
import org.springframework.beans.factory.InitializingBean;
void afterPropertiesSet() throws Exception {
System.out.println("LifeCycleBean initializing...");
}
}
在xml配置文件中並不需要對bean進行特殊的配置:
<beans>
編寫測試程序進行測試:
import org.springframework.beans.factory.xml.XmlBeanFactory;
public static void main(String[] args) {
XmlBeanFactory factory= new XmlBeanFactory( new ClassPathResource("com/spring/applicationcontext.xml"));
factory.getBean("lifeBean");
}
}
bean實現:
package com.spring;
publicvoid init(){
System. out .println("LifeCycleBean.init...");
}
}
在Spring配置文件中配置這個bean:
<bean name ="lifeBean" class ="research.spring.beanfactory.ch4.LifeCycleBean" init-method ="init"></bean>
</beans>
final protected void init() throws Exception{
throw new Exception("init exception");
}
調用代碼:
public class TestServiceConfigImpl implements InitializingBean {
private String folderName;
public void afterPropertiesSet()throws Exception{
folderName = folderName != null ? folderName : "test_config";
reload(folderName);
}
//根據文件目錄加載配置文件
public void reload(String fileName) throws Exception {
fileName = fileName.startsWith("/") ? fileName.substring(1) : fileName;
//根據文件名稱獲取相應的文件
File file = ResourceUtils.getFile("classpath:" + fileName);
for (File configFile : files) {
//加載文件……
}
}
}