在開發javaWeb系統時,有時需要在系統初始化時進行一些附帶的初始化操作,此時我們需要通過Spring獲取相應的bean對象,然後進行相應的初始化操作。現在總結如下幾種在系統初始化時獲取bean對象的方法
一、通過獲取WebApplicationContext直接得到bean
public class Applicationar {
public static WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
public static Object getBean (String beanName) {
Object bean;
bean =webApplicationContext.getBean(beanName);
return bean;
}
}
二、通過獲取ApplicationContext得到bean
實現ApplicationContextAware 接口來獲取ApplicationContext
@Service
public class SpringBean implements ApplicationContextAware {
public static ApplicationContext applicationContext ;
public static Object getBean (String beanName) {
return applicationContext.getBean(beanName);
}
//此處需要依賴注入
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringBean.applicationContext =applicationContext;
}
}
我採用的註解方式實現的spring註冊,也可以直接在xml文件中註冊。此處涉及到setApplicationContext,有依賴注入,所以必須要有bean的註冊。
ContextLoader的講解參照http://blog.csdn.net/zjw10wei321/article/details/40145241
servletContext和WebApplicationContext的相互獲取
public static WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
public static ServletContext servletContext = webApplicationContext.getServletContext();
ServletContext servletContext = event.getServletContext();
public WebApplicationContext web = WebApplicationContextUtils.getWebApplicationContext(servletContext);