在开发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);