赞
踩
在Spring中,InitializingBean
接口通常用于在Spring Bean的所有属性设置完后执行特定的初始化操作。这在某些特定场景下非常有用,并且被广泛使用。如下面这些使用场景:
InitializingBean
可以在所有依赖都注入好以后开始加载资源,防止因为依赖没有加载完全导致的问题。public class DataLoaderBean implements InitializingBean {
// DataSource object may be injected by Spring
private DataSource dataSource;
private CacheManager cacheManager;
@Override
public void afterPropertiesSet() throws Exception {
// Load data from DataSource
// Store data into CacheManager
}
// setters...
}
InitializingBean
就可以在所有属性设置完后,再进行这个属性的设定。public class DynamicPropertyBean implements InitializingBean {
private String propertyA;
private String propertyB;
private String combineProperty;
@Override
public void afterPropertiesSet() throws Exception {
// CombineProperty depends on PropertyA and PropertyB
combineProperty = propertyA + "-" + propertyB;
System.out.println("Combined property is initialized to: " + combineProperty);
}
// setters...
}
afterPropertiesSet
方法中进行一些状态检查。如果不满足条件,可以抛出异常中断和报错。public class StateCheckBean implements InitializingBean {
private OtherBean otherBean;
@Override
public void afterPropertiesSet() throws Exception {
if (otherBean.getStatus() != Status.READY) {
throw new Exception("StateCheckBean depends on OtherBean, but OtherBean's status is not ready yet.");
}
}
// setters...
}
以上三种场景都是InitializingBean
接口常见的使用情景。根据你的需求,你可以灵活运用InitializingBean
接口在Spring管理的Bean创建完成后执行一些初始化的工作。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。