Java Code Examples for org.springframework.web.context.ContextLoader

The following examples show how to use org.springframework.web.context.ContextLoader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: RequestContextUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source Project: spring-analysis-note   Source File: RedirectViewTests.java    License: MIT License 6 votes vote down vote up
@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);
	}
}
 
Example 3
Source Project: spring-analysis-note   Source File: SpringBeanAutowiringSupport.java    License: MIT License 6 votes vote down vote up
/**
 * 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.");
		}
	}
}
 
Example 4
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 5
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 6
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 7
Source Project: java-technology-stack   Source File: RequestContextUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source Project: java-technology-stack   Source File: RedirectViewTests.java    License: MIT License 6 votes vote down vote up
@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);
	}
}
 
Example 9
/**
 * 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.");
		}
	}
}
 
Example 10
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 12
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 13
Source Project: JwtPermission   Source File: SubjectUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取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;
}
 
Example 14
/**
 * 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.");
		}
	}
}
 
Example 15
/**
 * 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.");
		}
	}
}
 
Example 16
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 17
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 18
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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]"));
	}
}
 
Example 19
@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);
	
}
 
Example 20
@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);
	
}
 
Example 21
Source Project: spring-analysis-note   Source File: DispatcherServletTests.java    License: MIT License 5 votes vote down vote up
@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"));
}
 
Example 22
Source Project: spring-analysis-note   Source File: DispatcherServletTests.java    License: MIT License 5 votes vote down vote up
@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"));
}
 
Example 23
Source Project: spring-analysis-note   Source File: SpringConfiguratorTests.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 24
Source Project: spring-analysis-note   Source File: ContextLoaderTestUtils.java    License: MIT License 5 votes vote down vote up
@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);
	}
}
 
Example 25
/**
 * 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;
}
 
Example 26
Source Project: java-master   Source File: PortalController.java    License: Apache License 2.0 5 votes vote down vote up
@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";
}
 
Example 27
Source Project: java-technology-stack   Source File: DispatcherServletTests.java    License: MIT License 5 votes vote down vote up
@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"));
}
 
Example 28
Source Project: java-technology-stack   Source File: DispatcherServletTests.java    License: MIT License 5 votes vote down vote up
@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"));
}
 
Example 29
Source Project: java-technology-stack   Source File: SpringConfiguratorTests.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 30
Source Project: java-technology-stack   Source File: ContextLoaderTestUtils.java    License: MIT License 5 votes vote down vote up
@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);
	}
}