org.springframework.web.context.ContextLoader Java Examples

The following examples show how to use org.springframework.web.context.ContextLoader. 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 File: SubjectUtil.java    From JwtPermission with 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 #2
Source File: Spr8510Tests.java    From spring-analysis-note with 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 #3
Source File: SpringBeanAutowiringSupport.java    From spring-analysis-note with 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 File: BootFrontEndApplicationConfigurator.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: RedirectViewTests.java    From spring-analysis-note with 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 #6
Source File: Spr8510Tests.java    From spring-analysis-note with 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 #7
Source File: Spr8510Tests.java    From spring-analysis-note with 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 #8
Source File: RequestContextUtils.java    From spring-analysis-note with 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 #9
Source File: BootFrontEndApplicationConfigurator.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: Spr8510Tests.java    From spring4-understanding with 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 #11
Source File: SpringBeanAutowiringSupport.java    From spring4-understanding with Apache License 2.0 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 #12
Source File: RequestContextUtils.java    From java-technology-stack with 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 #13
Source File: Spr8510Tests.java    From spring4-understanding with 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 #14
Source File: RedirectViewTests.java    From java-technology-stack with 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 #15
Source File: SpringBeanAutowiringSupport.java    From java-technology-stack with 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 #16
Source File: SpringBeanAutowiringSupport.java    From lams with GNU General Public License v2.0 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 #17
Source File: Spr8510Tests.java    From java-technology-stack with 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 #18
Source File: Spr8510Tests.java    From java-technology-stack with 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 #19
Source File: Spr8510Tests.java    From java-technology-stack with 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 #20
Source File: Spr8510Tests.java    From spring4-understanding with 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 #21
Source File: ResponseFactory.java    From dpCms with Apache License 2.0 5 votes vote down vote up
private static void initValidator() {
	if (validator == null) {
		WebApplicationContext wac = ContextLoader
				.getCurrentWebApplicationContext();
		ValidatorFactory validatorFactory = (ValidatorFactory) wac
				.getBean("validator");
		validator = validatorFactory.getValidator();
	}
}
 
Example #22
Source File: ContextLoaderTestUtils.java    From spring4-understanding with Apache License 2.0 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 #23
Source File: SpringWebConstraintValidatorFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: HelloWorldSecureController.java    From tutorials with MIT License 5 votes vote down vote up
private void processContext() {
    ApplicationContext context = contextUtilService.getApplicationContext();
    System.out.println("application context : " + context);
    System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames()));
    
    WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
    System.out.println("context : " + rootContext);
    System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));

    System.out.println("context : " + webApplicationContext);
    System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
 
Example #25
Source File: SpringWebConstraintValidatorFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 File: ConfigTestUtils.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Crea e restituisce il Contesto dell'Applicazione.
 *
 * @param srvCtx Il Contesto della Servlet.
 * @return Il Contesto dell'Applicazione.
 */
public ApplicationContext createApplicationContext(ServletContext srvCtx) {
    this.createNamingContext();
    XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
    applicationContext.setConfigLocations(this.getSpringConfigFilePaths());
    applicationContext.setServletContext(srvCtx);
    ContextLoader contextLoader = new ContextLoader(applicationContext);
    contextLoader.initWebApplicationContext(srvCtx);
    applicationContext.refresh();
    return applicationContext;
}
 
Example #27
Source File: StartupListenerTest.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
// @Before
public void setUp() throws Exception {
	sc = new MockServletContext("");

	// initialize Spring
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"classpath:/applicationContext-dao.xml, "
					+ "classpath:/applicationContext-service.xml");

	springListener = new ContextLoaderListener();
	springListener.contextInitialized(new ServletContextEvent(sc));
	listener = new StartupListener();

}
 
Example #28
Source File: ConfigGitRepoFilter.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public void init(FilterConfig config) throws ServletException {
    ConfigRepository configRepository = ContextLoader.getCurrentWebApplicationContext().getBean(ConfigRepository.class);
    FileResolver<HttpServletRequest> resolver = new FileResolver<>();
    resolver.exportRepository("api/config-repository.git", configRepository.getGitRepo());
    setRepositoryResolver(resolver);
    setReceivePackFactory(null);

    super.init(config);

}
 
Example #29
Source File: HelloWorldController.java    From tutorials with MIT License 5 votes vote down vote up
private void processContext() {
    WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
    
    System.out.println("root context : " + rootContext);
    System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));

    System.out.println("context : " + webApplicationContext);
    System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
 
Example #30
Source File: SpringConfiguratorTests.java    From spring4-understanding with Apache License 2.0 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();
}