Java tutorial
/** * Copyright (c) 2005-2011 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: SpringWebTestUtils.java 1594 2011-05-11 14:22:29Z calvinxiu $ */ package cn.hxh.springside.test.utils; import org.apache.commons.lang.StringUtils; import org.springframework.context.ApplicationContext; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; /** * Spring WebApplicationContext?ServletContext?. * * @author calvin */ public abstract class SpringWebTestUtils { /** * ServletContext?Spring WebApplicationContext. * * @param configLocations application context. */ public static void initWebApplicationContext(MockServletContext servletContext, String... configLocations) { String configLocationsString = StringUtils.join(configLocations, ","); servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, configLocationsString); new ContextLoader().initWebApplicationContext(servletContext); } /** * ServletContext?Spring WebApplicationContext. * * @param applicationContext ApplicationContext. */ public static void initWebApplicationContext(MockServletContext servletContext, ApplicationContext applicationContext) { ConfigurableWebApplicationContext wac = new XmlWebApplicationContext(); wac.setParent(applicationContext); wac.setServletContext(servletContext); wac.setConfigLocation(""); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); wac.refresh(); } /** * ServletContextSpring WebApplicationContext. */ public static void closeWebApplicationContext(MockServletContext servletContext) { new ContextLoader().closeWebApplicationContext(servletContext); } }