在web项目中获取spring上下文

获取原因:在一方法类中需要用到另一个变量实例,尝试多种方法均失败,故而采用获取spring上下文方法,在需要的地方从spring容器中获取该Bean的方法。注:不是最好的方法,但是是管用的


public class Main implements ServletContextListener {

private Logger logger = Logger.getLogger(this.getClass().getName());


@Override
public void contextInitialized(ServletContextEvent event) {
try {
//获取spring上下文
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
BeanUtil.setApplication(context);
} catch (Exception e) {
logger.error("系统启动失败.", e);
System.exit(1);
}

logger.info("系统启动成功!");

}



public class BeanUtil {
private static ApplicationContext applicationContext = null;

public static void setApplication(ApplicationContext application){
applicationContext = application;
}

public static Object getBean(String beanId) {
return applicationContext.getBean(beanId);
}

}

你可能感兴趣的:(在web项目中获取spring上下文)