Java Code Examples for org.springframework.web.context.support.GenericWebApplicationContext#refresh()

The following examples show how to use org.springframework.web.context.support.GenericWebApplicationContext#refresh() . 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: JdkProxyControllerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor(true)));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 2
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer();
	bindingInitializer.setValidator(new StubValidator());

	List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<>();
	customResolvers.add(new ServletWebArgumentResolverAdapter(new ColorArgumentResolver()));

	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();

	handlerAdapter = new RequestMappingHandlerAdapter();
	handlerAdapter.setWebBindingInitializer(bindingInitializer);
	handlerAdapter.setCustomArgumentResolvers(customResolvers);
	handlerAdapter.setApplicationContext(context);
	handlerAdapter.setBeanFactory(context.getBeanFactory());
	handlerAdapter.afterPropertiesSet();

	request = new MockHttpServletRequest();
	response = new MockHttpServletResponse();

	request.setMethod("POST");

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(request));
}
 
Example 3
Source File: JdkProxyControllerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor(true)));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 4
Source File: PortletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void standardHandleMethod() throws Exception {
	DispatcherPortlet portlet = new DispatcherPortlet() {
		@Override
		protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class));
			wac.refresh();
			return wac;
		}
	};
	portlet.init(new MockPortletConfig());

	MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
	MockRenderResponse response = new MockRenderResponse();
	portlet.render(request, response);
	assertEquals("test", response.getContentAsString());
}
 
Example 5
Source File: HandlerMethodAnnotationDetectionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public HandlerMethodAnnotationDetectionTests(Class<?> controllerType, boolean useAutoProxy) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.registerBeanDefinition("controller", new RootBeanDefinition(controllerType));
	context.registerBeanDefinition("handlerMapping", new RootBeanDefinition(RequestMappingHandlerMapping.class));
	context.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(RequestMappingHandlerAdapter.class));
	context.registerBeanDefinition("exceptionResolver", new RootBeanDefinition(ExceptionHandlerExceptionResolver.class));
	if (useAutoProxy) {
		DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
		autoProxyCreator.setBeanFactory(context.getBeanFactory());
		context.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
		context.registerBeanDefinition("controllerAdvice", new RootBeanDefinition(ControllerAdvisor.class));
	}
	context.refresh();

	this.handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
	this.handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class);
	this.exceptionResolver = context.getBean(ExceptionHandlerExceptionResolver.class);
	context.close();
}
 
Example 6
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void emptyRequestMapping() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerWithEmptyMapping.class));
			RootBeanDefinition mbd = new RootBeanDefinition(ControllerClassNameHandlerMapping.class);
			mbd.getPropertyValues().add("excludedPackages", null);
			mbd.getPropertyValues().add("order", 0);
			wac.registerBeanDefinition("mapping", mbd);
			wac.registerBeanDefinition("mapping2", new RootBeanDefinition(DefaultAnnotationHandlerMapping.class));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/servletannotationcontrollertests.controllerwithemptymapping");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("test", response.getContentAsString());
}
 
Example 7
Source File: ExpressionValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());

	Method method = getClass().getMethod("params", int.class, String.class, String.class);
	paramSystemProperty = new MethodParameter(method, 0);
	paramContextPath = new MethodParameter(method, 1);
	paramNotSupported = new MethodParameter(method, 2);

	webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example 8
Source File: HandlerMethodAnnotationDetectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public HandlerMethodAnnotationDetectionTests(final Class<?> controllerType, boolean useAutoProxy) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.registerBeanDefinition("controller", new RootBeanDefinition(controllerType));
	context.registerBeanDefinition("handlerMapping", new RootBeanDefinition(RequestMappingHandlerMapping.class));
	context.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(RequestMappingHandlerAdapter.class));
	context.registerBeanDefinition("exceptionResolver", new RootBeanDefinition(ExceptionHandlerExceptionResolver.class));
	if (useAutoProxy) {
		DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
		autoProxyCreator.setBeanFactory(context.getBeanFactory());
		context.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
		context.registerBeanDefinition("controllerAdvice", new RootBeanDefinition(ControllerAdvisor.class));
	}
	context.refresh();

	this.handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
	this.handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class);
	this.exceptionResolver = context.getBean(ExceptionHandlerExceptionResolver.class);
	context.close();
}
 
Example 9
Source File: CglibProxyControllerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerClass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setProxyTargetClass(true);
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			Pointcut pointcut = new AnnotationMatchingPointcut(Controller.class);
			DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleTraceInterceptor(true));
			wac.getBeanFactory().registerSingleton("advisor", advisor);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 10
Source File: PortletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void mavResolver() throws Exception {
	DispatcherPortlet portlet = new DispatcherPortlet() {
		@Override
		protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller",
					new RootBeanDefinition(ModelAndViewResolverController.class));
			RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
			adapterDef.getPropertyValues()
					.add("customModelAndViewResolver", new MyModelAndViewResolver());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
			wac.refresh();
			return wac;
		}
	};
	portlet.init(new MockPortletConfig());

	MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
	MockRenderResponse response = new MockRenderResponse();
	portlet.render(request, response);
}
 
Example 11
Source File: AbstractJettyComponent.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent)
{
	GenericWebApplicationContext wac = (GenericWebApplicationContext) BeanUtils.instantiateClass(GenericWebApplicationContext.class);

	// Assign the best possible id value.
	wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + contextPath);

	wac.setParent(parent);
	wac.setServletContext(sc);
	wac.refresh();

	return wac;
}
 
Example 12
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void responseBodyNoAcceptableMediaType() throws ServletException, IOException {
	@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class));
			RootBeanDefinition converterDef = new RootBeanDefinition(StringHttpMessageConverter.class);
			converterDef.getPropertyValues().add("supportedMediaTypes", new MediaType("text", "plain"));
			RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
			StringHttpMessageConverter converter = new StringHttpMessageConverter();
			converter.setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "plain")));
			adapterDef.getPropertyValues().add("messageConverters", converter);
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.addHeader("Accept", "application/pdf, application/msword");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals(406, response.getStatus());
}
 
Example 13
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void webApplicationContext() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
	assertHasStandardServletEnvironment(ctx);
	ctx.setEnvironment(prodWebEnv);
	ctx.refresh();

	assertHasEnvironment(ctx, prodWebEnv);
	assertEnvironmentBeanRegistered(ctx);
	assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
 
Example 14
Source File: PortletApplicationContextScopeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private ConfigurablePortletApplicationContext initApplicationContext(String scope) {
	MockServletContext sc = new MockServletContext();
	GenericWebApplicationContext rac = new GenericWebApplicationContext(sc);
	rac.refresh();
	PortletContext pc = new ServletWrappingPortletContext(sc);
	StaticPortletApplicationContext ac = new StaticPortletApplicationContext();
	ac.setParent(rac);
	ac.setPortletContext(pc);
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(DerivedTestBean.class);
	bd.setScope(scope);
	ac.registerBeanDefinition(NAME, bd);
	ac.refresh();
	return ac;
}
 
Example 15
Source File: WebApplicationContextScopeTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private WebApplicationContext initApplicationContext(String scope) {
	MockServletContext sc = new MockServletContext();
	GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(DerivedTestBean.class);
	bd.setScope(scope);
	ac.registerBeanDefinition(NAME, bd);
	ac.refresh();
	return ac;
}
 
Example 16
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator((definition, registry) -> definition.getScope());
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
Example 17
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void webApplicationContext() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
	assertHasStandardServletEnvironment(ctx);
	ctx.setEnvironment(prodWebEnv);
	ctx.refresh();

	assertHasEnvironment(ctx, prodWebEnv);
	assertEnvironmentBeanRegistered(ctx);
	assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
 
Example 18
Source File: XmlViewResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Initialize the view bean factory from the XML file.
 * Synchronized because of access by parallel threads.
 * @throws BeansException in case of initialization errors
 */
protected synchronized BeanFactory initFactory() throws BeansException {
	if (this.cachedFactory != null) {
		return this.cachedFactory;
	}

	ApplicationContext applicationContext = obtainApplicationContext();

	Resource actualLocation = this.location;
	if (actualLocation == null) {
		actualLocation = applicationContext.getResource(DEFAULT_LOCATION);
	}

	// Create child ApplicationContext for views.
	GenericWebApplicationContext factory = new GenericWebApplicationContext();
	factory.setParent(applicationContext);
	factory.setServletContext(getServletContext());

	// Load XML resource with context-aware entity resolver.
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
	reader.setEnvironment(applicationContext.getEnvironment());
	reader.setEntityResolver(new ResourceEntityResolver(applicationContext));
	reader.loadBeanDefinitions(actualLocation);

	factory.refresh();

	if (isCache()) {
		this.cachedFactory = factory;
	}
	return factory;
}
 
Example 19
Source File: AbstractServletHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize a DispatcherServlet instance registering zero or more controller classes
 * and also providing additional bean definitions through a callback.
 */
@SuppressWarnings("serial")
protected WebApplicationContext initServlet(
		final ApplicationContextInitializer<GenericWebApplicationContext> initializer,
		final Class<?>... controllerClasses) throws ServletException {

	final GenericWebApplicationContext wac = new GenericWebApplicationContext();

	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			for (Class<?> clazz : controllerClasses) {
				wac.registerBeanDefinition(clazz.getSimpleName(), new RootBeanDefinition(clazz));
			}

			Class<?> mappingType = RequestMappingHandlerMapping.class;
			RootBeanDefinition beanDef = new RootBeanDefinition(mappingType);
			beanDef.getPropertyValues().add("removeSemicolonContent", "false");
			wac.registerBeanDefinition("handlerMapping", beanDef);

			Class<?> adapterType = RequestMappingHandlerAdapter.class;
			wac.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(adapterType));

			Class<?> resolverType = ExceptionHandlerExceptionResolver.class;
			wac.registerBeanDefinition("requestMappingResolver", new RootBeanDefinition(resolverType));

			resolverType = ResponseStatusExceptionResolver.class;
			wac.registerBeanDefinition("responseStatusResolver", new RootBeanDefinition(resolverType));

			resolverType = DefaultHandlerExceptionResolver.class;
			wac.registerBeanDefinition("defaultResolver", new RootBeanDefinition(resolverType));

			if (initializer != null) {
				initializer.initialize(wac);
			}

			wac.refresh();
			return wac;
		}
	};

	servlet.init(new MockServletConfig());

	return wac;
}
 
Example 20
Source File: AbstractGenericWebContextLoader.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Load a Spring {@link WebApplicationContext} from the supplied
 * {@link MergedContextConfiguration}.
 *
 * <p>Implementation details:
 *
 * <ul>
 * <li>Calls {@link #validateMergedContextConfiguration(WebMergedContextConfiguration)}
 * to allow subclasses to validate the supplied configuration before proceeding.</li>
 * <li>Creates a {@link GenericWebApplicationContext} instance.</li>
 * <li>If the supplied {@code MergedContextConfiguration} references a
 * {@linkplain MergedContextConfiguration#getParent() parent configuration},
 * the corresponding {@link MergedContextConfiguration#getParentApplicationContext()
 * ApplicationContext} will be retrieved and
 * {@linkplain GenericWebApplicationContext#setParent(ApplicationContext) set as the parent}
 * for the context created by this method.</li>
 * <li>Delegates to {@link #configureWebResources} to create the
 * {@link MockServletContext} and set it in the {@code WebApplicationContext}.</li>
 * <li>Calls {@link #prepareContext} to allow for customizing the context
 * before bean definitions are loaded.</li>
 * <li>Calls {@link #customizeBeanFactory} to allow for customizing the
 * context's {@code DefaultListableBeanFactory}.</li>
 * <li>Delegates to {@link #loadBeanDefinitions} to populate the context
 * from the locations or classes in the supplied {@code MergedContextConfiguration}.</li>
 * <li>Delegates to {@link AnnotationConfigUtils} for
 * {@linkplain AnnotationConfigUtils#registerAnnotationConfigProcessors registering}
 * annotation configuration processors.</li>
 * <li>Calls {@link #customizeContext} to allow for customizing the context
 * before it is refreshed.</li>
 * <li>{@link ConfigurableApplicationContext#refresh Refreshes} the
 * context and registers a JVM shutdown hook for it.</li>
 * </ul>
 *
 * @return a new web application context
 * @see org.springframework.test.context.SmartContextLoader#loadContext(MergedContextConfiguration)
 * @see GenericWebApplicationContext
 */
@Override
public final ConfigurableApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {

	if (!(mergedConfig instanceof WebMergedContextConfiguration)) {
		throw new IllegalArgumentException(String.format(
			"Cannot load WebApplicationContext from non-web merged context configuration %s. "
					+ "Consider annotating your test class with @WebAppConfiguration.", mergedConfig));
	}
	WebMergedContextConfiguration webMergedConfig = (WebMergedContextConfiguration) mergedConfig;

	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Loading WebApplicationContext for merged context configuration %s.",
			webMergedConfig));
	}

	validateMergedContextConfiguration(webMergedConfig);

	GenericWebApplicationContext context = new GenericWebApplicationContext();

	ApplicationContext parent = mergedConfig.getParentApplicationContext();
	if (parent != null) {
		context.setParent(parent);
	}
	configureWebResources(context, webMergedConfig);
	prepareContext(context, webMergedConfig);
	customizeBeanFactory(context.getDefaultListableBeanFactory(), webMergedConfig);
	loadBeanDefinitions(context, webMergedConfig);
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	customizeContext(context, webMergedConfig);
	context.refresh();
	context.registerShutdownHook();
	return context;
}