您的位置:首页 > 其它

Web容器初始化时获取bean的几种方法

2016-02-23 09:39 302 查看
在开发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的讲解参照/article/11144512.html

servletContext和WebApplicationContext的相互获取

public static WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

public static ServletContext servletContext = webApplicationContext.getServletContext();

ServletContext servletContext = event.getServletContext();

public WebApplicationContext web = WebApplicationContextUtils.getWebApplicationContext(servletContext);



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: