org.springframework.web.servlet.support.RequestDataValueProcessorWrapper#org.springframework.web.context.ContextLoader源码实例Demo

下面列出了org.springframework.web.servlet.support.RequestDataValueProcessorWrapper#org.springframework.web.context.ContextLoader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Look for the WebApplicationContext associated with the DispatcherServlet
 * that has initiated request processing, and for the global context if none
 * was found associated with the current request. The global context will
 * be found via the ServletContext or via ContextLoader's current context.
 * <p>NOTE: This variant remains compatible with Servlet 2.5, explicitly
 * checking a given ServletContext instead of deriving it from the request.
 * @param request current HTTP request
 * @param servletContext current servlet context
 * @return the request-specific WebApplicationContext, or the global one
 * if no request-specific context has been found, or {@code null} if none
 * @since 4.2.1
 * @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE
 * @see WebApplicationContextUtils#getWebApplicationContext(ServletContext)
 * @see ContextLoader#getCurrentWebApplicationContext()
 */
@Nullable
public static WebApplicationContext findWebApplicationContext(
		HttpServletRequest request, @Nullable ServletContext servletContext) {

	WebApplicationContext webApplicationContext = (WebApplicationContext) request.getAttribute(
			DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	if (webApplicationContext == null) {
		if (servletContext != null) {
			webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		}
		if (webApplicationContext == null) {
			webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		}
	}
	return webApplicationContext;
}
 
源代码2 项目: spring-analysis-note   文件: RedirectViewTests.java
@Test
public void updateTargetUrlWithContextLoader() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);

	MockServletContext servletContext = new MockServletContext();
	ContextLoader contextLoader = new ContextLoader(wac);
	contextLoader.initWebApplicationContext(servletContext);

	try {
		RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
		wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

		RedirectView rv = new RedirectView();
		rv.setUrl("/path");

		given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");
		rv.render(new ModelMap(), request, response);
		verify(mockProcessor).processUrl(request, "/path");
	}
	finally {
		contextLoader.closeWebApplicationContext(servletContext);
	}
}
 
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
	Assert.notNull(target, "Target object must not be null");
	WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
	if (cc != null) {
		AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
		bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
		bpp.processInjection(target);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Current WebApplicationContext is not available for processing of " +
					ClassUtils.getShortName(target.getClass()) + ": " +
					"Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
		}
	}
}
 
源代码4 项目: spring-analysis-note   文件: Spr8510Tests.java
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码5 项目: spring-analysis-note   文件: Spr8510Tests.java
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码6 项目: spring-analysis-note   文件: Spr8510Tests.java
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
		@Override
		protected String[] getDefaultConfigLocations() {
			return new String[] { "/WEB-INF/custom.xml" };
		}
	};
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
/**
 * Look for the WebApplicationContext associated with the DispatcherServlet
 * that has initiated request processing, and for the global context if none
 * was found associated with the current request. The global context will
 * be found via the ServletContext or via ContextLoader's current context.
 * <p>NOTE: This variant remains compatible with Servlet 2.5, explicitly
 * checking a given ServletContext instead of deriving it from the request.
 * @param request current HTTP request
 * @param servletContext current servlet context
 * @return the request-specific WebApplicationContext, or the global one
 * if no request-specific context has been found, or {@code null} if none
 * @since 4.2.1
 * @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE
 * @see WebApplicationContextUtils#getWebApplicationContext(ServletContext)
 * @see ContextLoader#getCurrentWebApplicationContext()
 */
@Nullable
public static WebApplicationContext findWebApplicationContext(
		HttpServletRequest request, @Nullable ServletContext servletContext) {

	WebApplicationContext webApplicationContext = (WebApplicationContext) request.getAttribute(
			DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	if (webApplicationContext == null) {
		if (servletContext != null) {
			webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		}
		if (webApplicationContext == null) {
			webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		}
	}
	return webApplicationContext;
}
 
源代码8 项目: java-technology-stack   文件: RedirectViewTests.java
@Test
public void updateTargetUrlWithContextLoader() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);

	MockServletContext servletContext = new MockServletContext();
	ContextLoader contextLoader = new ContextLoader(wac);
	contextLoader.initWebApplicationContext(servletContext);

	try {
		RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
		wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

		RedirectView rv = new RedirectView();
		rv.setUrl("/path");

		given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");
		rv.render(new ModelMap(), request, response);
		verify(mockProcessor).processUrl(request, "/path");
	}
	finally {
		contextLoader.closeWebApplicationContext(servletContext);
	}
}
 
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
	Assert.notNull(target, "Target object must not be null");
	WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
	if (cc != null) {
		AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
		bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
		bpp.processInjection(target);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Current WebApplicationContext is not available for processing of " +
					ClassUtils.getShortName(target.getClass()) + ": " +
					"Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
		}
	}
}
 
源代码10 项目: java-technology-stack   文件: Spr8510Tests.java
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码11 项目: java-technology-stack   文件: Spr8510Tests.java
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码12 项目: java-technology-stack   文件: Spr8510Tests.java
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
		@Override
		protected String[] getDefaultConfigLocations() {
			return new String[] { "/WEB-INF/custom.xml" };
		}
	};
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码13 项目: JwtPermission   文件: SubjectUtil.java
/**
 * 获取Bean
 */
public static <T> T getBean(Class<T> clazz) {
    try {
        WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
        if (applicationContext == null) return null;
        ServletContext servletContext = applicationContext.getServletContext();
        if (servletContext == null) return null;
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if (context == null) return null;
        Collection<T> beans = context.getBeansOfType(clazz).values();
        while (beans.iterator().hasNext()) {
            T bean = beans.iterator().next();
            if (bean != null) return bean;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
源代码14 项目: lams   文件: SpringBeanAutowiringSupport.java
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
	Assert.notNull(target, "Target object must not be null");
	WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
	if (cc != null) {
		AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
		bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
		bpp.processInjection(target);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Current WebApplicationContext is not available for processing of " +
					ClassUtils.getShortName(target.getClass()) + ": " +
					"Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
		}
	}
}
 
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
	Assert.notNull(target, "Target object must not be null");
	WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
	if (cc != null) {
		AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
		bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
		bpp.processInjection(target);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Current WebApplicationContext is not available for processing of " +
					ClassUtils.getShortName(target.getClass()) + ": " +
					"Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
		}
	}
}
 
源代码16 项目: spring4-understanding   文件: Spr8510Tests.java
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码17 项目: spring4-understanding   文件: Spr8510Tests.java
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
源代码18 项目: spring4-understanding   文件: Spr8510Tests.java
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
		@Override
		protected String[] getDefaultConfigLocations() {
			return new String[] { "/WEB-INF/custom.xml" };
		}
	};
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
	
	ModuleDataExtractor extractor = new ModuleDataExtractor(module);
	microserverEnvironment.assureModule(module);
	String fullRestResource = "/" + module.getContext() + "/*";

	ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
			Arrays.asList(),
			rootContext, fullRestResource, module);
	List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
	List<ServletData> servletDataList = extractor.createServletDataList(serverData);
	new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);

	new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
	PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
    PersistentList<ServletRequestListener> servletRequestListenerData =	LinkedListX.fromIterable(module.getRequestListeners(serverData));
	
	new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
	
}
 
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
	
	ModuleDataExtractor extractor = new ModuleDataExtractor(module);
	microserverEnvironment.assureModule(module);
	String fullRestResource = "/" + module.getContext() + "/*";

	ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
			Arrays.asList(),
			rootContext, fullRestResource, module);
	List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
	List<ServletData> servletDataList = extractor.createServletDataList(serverData);
	new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);

	new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
	PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
    PersistentList<ServletRequestListener> servletRequestListenerData =	LinkedListX.fromIterable(module.getRequestListeners(serverData));
	
	new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
	
}
 
@Test
public void globalInitializerClasses() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextClass(SimpleWebApplicationContext.class);
	getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
			TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName());
	servlet.init(servletConfig);
	assertEquals("true", getServletContext().getAttribute("initialized"));
	assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
 
@Test
public void mixedInitializerClasses() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextClass(SimpleWebApplicationContext.class);
	getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
			TestWebContextInitializer.class.getName());
	servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName());
	servlet.init(servletConfig);
	assertEquals("true", getServletContext().getAttribute("initialized"));
	assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
 
@Before
public void setup() {
	this.servletContext = new MockServletContext();

	this.webAppContext = new AnnotationConfigWebApplicationContext();
	this.webAppContext.register(Config.class);

	this.contextLoader = new ContextLoader(this.webAppContext);
	this.contextLoader.initWebApplicationContext(this.servletContext);

	this.configurator = new SpringConfigurator();
}
 
@SuppressWarnings("unchecked")
private static Map<ClassLoader, WebApplicationContext> getCurrentContextPerThreadFromContextLoader() {
	try {
		Field field = ContextLoader.class.getDeclaredField("currentContextPerThread");
		field.setAccessible(true);
		return (Map<ClassLoader, WebApplicationContext>) field.get(null);
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
/**
 * Retrieve the Spring {@link WebApplicationContext} to use.
 * The default implementation returns the current {@link WebApplicationContext}
 * as registered for the thread context class loader.
 * @return the current WebApplicationContext (never {@code null})
 * @see ContextLoader#getCurrentWebApplicationContext()
 */
protected WebApplicationContext getWebApplicationContext() {
	WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
	if (wac == null) {
		throw new IllegalStateException("No WebApplicationContext registered for current thread - " +
				"consider overriding SpringWebConstraintValidatorFactory.getWebApplicationContext()");
	}
	return wac;
}
 
源代码26 项目: java-master   文件: PortalController.java
@GetMapping("/index")
@ResponseBody
public String index(HttpServletRequest request) {
    ApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();

    ServletContext servletContext = request.getSession().getServletContext();
    ApplicationContext applicationContext1 = (ApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    System.out.println(applicationContext == applicationContext1);

    System.out.println(applicationContext == context.getParent());

    return "hello world";
}
 
@Test
public void globalInitializerClasses() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextClass(SimpleWebApplicationContext.class);
	getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
			TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName());
	servlet.init(servletConfig);
	assertEquals("true", getServletContext().getAttribute("initialized"));
	assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
 
@Test
public void mixedInitializerClasses() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextClass(SimpleWebApplicationContext.class);
	getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
			TestWebContextInitializer.class.getName());
	servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName());
	servlet.init(servletConfig);
	assertEquals("true", getServletContext().getAttribute("initialized"));
	assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
 
@Before
public void setup() {
	this.servletContext = new MockServletContext();

	this.webAppContext = new AnnotationConfigWebApplicationContext();
	this.webAppContext.register(Config.class);

	this.contextLoader = new ContextLoader(this.webAppContext);
	this.contextLoader.initWebApplicationContext(this.servletContext);

	this.configurator = new SpringConfigurator();
}
 
@SuppressWarnings("unchecked")
private static Map<ClassLoader, WebApplicationContext> getCurrentContextPerThreadFromContextLoader() {
	try {
		Field field = ContextLoader.class.getDeclaredField("currentContextPerThread");
		field.setAccessible(true);
		return (Map<ClassLoader, WebApplicationContext>) field.get(null);
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}