InitializingBean
spring的InitializingBean为bean提供了定义初始化方法的方式。InitializingBean是一个接口,只包含一个方法:afterPropertiesSet():
public interface InitializingBean
{
public abstract void afterPropertiesSet()
throws Exception;
}
import org.springframework.beans.factory.InitializingBean;
publicclass LifeCycleBean implements InitializingBean{
void afterPropertiesSet() throws Exception {
System.out.println("LifeCycleBean initializing...");
}
}
在xml配置文件中并不需要对bean进行特殊的配置:
编写测试程序进行测试:
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class LifeCycleTest {
public static void main(String[] args) {
XmlBeanFactory factory= new XmlBeanFactory( new ClassPathResource("com/spring/applicationcontext.xml"));
factory.getBean("lifeBean");
}
}
package com.spring;
public class LifeCycleBean{
publicvoid init(){
System. out .println("LifeCycleBean.init...");
}
}
在Spring配置文件中配置这个bean:
final protected void init() throws Exception{
System.out.println("init method...");
if(true)
throw new Exception("init exception");
}
//bean装配完成之后,执行bean初始化方法
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable
{
//判断bean是否实现了InitializingBean接口
boolean isInitializingBean = bean instanceof InitializingBean;
if(isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet")))
{
if(logger.isDebugEnabled())
logger.debug((new StringBuilder()).append("Invoking afterPropertiesSet() on bean with name '").append(beanName).append("'").toString());
if(System.getSecurityManager() != null)
try
{
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run()
throws Exception
{
//调用afterPropertiesSet方法
((InitializingBean)bean).afterPropertiesSet();
return null;
}
final Object val$bean;
final AbstractAutowireCapableBeanFactory this$0;
{
this.this$0 = AbstractAutowireCapableBeanFactory.this;
bean = obj;
super();
}
}
, getAccessControlContext());
}
catch(PrivilegedActionException pae)
{
throw pae.getException();
}
else
((InitializingBean)bean).afterPropertiesSet();////调用afterPropertiesSet方法
}
if(mbd != null)
{
//判断bean是否定义了init-method方法
String initMethodName = mbd.getInitMethodName();
if(initMethodName != null && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName))
//调用invokeCustomInitMethod方法来执行init-method定义的方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
//执行bean定义的init-method方法
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable
{
String initMethodName = mbd.getInitMethodName();
//使用方法名,反射Method对象
final Method initMethod = mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName, new Class[0]) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName, new Class[0]);
if(initMethod == null)
{
if(mbd.isEnforceInitMethod())
throw new BeanDefinitionValidationException((new StringBuilder()).append("Couldn't find an init method named '").append(initMethodName).append("' on bean with name '").append(beanName).append("'").toString());
if(logger.isDebugEnabled())
logger.debug((new StringBuilder()).append("No default init method named '").append(initMethodName).append("' found on bean with name '").append(beanName).append("'").toString());
return;
}
if(logger.isDebugEnabled())
logger.debug((new StringBuilder()).append("Invoking init method '").append(initMethodName).append("' on bean with name '").append(beanName).append("'").toString());
if(System.getSecurityManager() != null)
{
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run()
throws Exception
{
ReflectionUtils.makeAccessible(initMethod);
return null;
}
final Method val$initMethod;
final AbstractAutowireCapableBeanFactory this$0;
{
this.this$0 = AbstractAutowireCapableBeanFactory.this;
initMethod = method;
super();
}
}
);
try
{
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run()
throws Exception
{
initMethod.invoke(bean, new Object[0]);//反射执行init-method方法
return null;
}
final Method val$initMethod;
final Object val$bean;
final AbstractAutowireCapableBeanFactory this$0;
{
this.this$0 = AbstractAutowireCapableBeanFactory.this;
initMethod = method;
bean = obj;
super();
}
}
, getAccessControlContext());
}
catch(PrivilegedActionException pae)
{
InvocationTargetException ex = (InvocationTargetException)pae.getException();
throw ex.getTargetException();
}
} else
{
try
{
ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean, new Object[0]);//反射执行init-method方法
}
catch(InvocationTargetException ex)
{
throw ex.getTargetException();
}
}
}
调用代码:
//bean初始化之后调用afterPropertiesSet方法根据配置目录,读取相应目录下的配置文件
public class TestServiceConfigImpl implements InitializingBean {
private String folderName;
@Override
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);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File configFile : files) {
//加载文件……
}
}
}
}