InitializingBean与ServletContextA
2018-08-28 本文已影响532人
ZMRWEGo
一、InitializingBean
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法。例如我们在一个项目启动时要创建一个lucene索引:
@Service
public class SystemLoadInit implements InitializingBean,ServletContextAware {
@Autowired
DataIndex dataIndex;
@Autowired
LuceneIndex luceneIndex;
private final Logger logger = LogManager.getLogger("info");
@Override
public void afterPropertiesSet() throws Exception {
// logger.info("开始创建索引");
luceneIndex.deleteAllIndex("shoe");
luceneIndex.deleteAllIndex("sale");
dataIndex.create();
dataIndex.update();
}
@Override
public void setServletContext(ServletContext servletContext) {
}
}
在spring初始化bean的时候,如果bean实现了InitializingBean接口,会自动调用afterPropertiesSet方法。还有一种方法是在配置文件中设置:
<bean id="testInitializingBean" class="SystemLoadInit" init-method="testInit"></bean>
通过查看spring的源码,我们可以看出两者之间的区别,AbstractAutowireCapableBeanFactory类中的invokeInitMethods讲解的非常清楚,源码如下:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
//判断该bean是否实现了实现了InitializingBean接口,如果实现了InitializingBean接口,则只掉调用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<Object>() {
public Object run() throws Exception {
//直接调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}
},getAccessControlContext());
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//直接调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
//判断是否指定了init-method方法,如果指定了init-method方法,则再调用制定的init-method
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//进一步查看该方法的源码,可以发现init-method方法中指定的方法是通过反射实现
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
二、ServletContextAware
ServeletContextAware继承自Aware接口,当一个类继承了ServletContextAware接口后,它就可以取得servletContex对象,我们可以利用它来给ServletContext初始化对象:
public class PropertyHolder implements ServletContextAware{
private static ServletContext servletContext;
/**
* 给上下文设置值
*/
@Override
public void setServletContext(ServletContext servletContext) {
PropertyHolder.servletContext = servletContext;
servletContext.setAttribute("ctx", servletContext.getContextPath());
}