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) {
//加载文件……
}
}
}