Java Code Examples for org.springframework.context.ApplicationContextInitializer

The following examples show how to use org.springframework.context.ApplicationContextInitializer. 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
@Test
public void specificBinderInitializingCommandProvidingFormController() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
		}
	}, MySpecificBinderInitializingCommandProvidingFormController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("defaultName", "myDefaultName");
	request.addParameter("age", "value2");
	request.addParameter("date", "2007-10-02");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
 
Example 2
@Test
public void commandProvidingFormControllerWithCustomEditor() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, MyCommandProvidingFormController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("defaultName", "myDefaultName");
	request.addParameter("age", "value2");
	request.addParameter("date", "2007-10-02");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
 
Example 3
Source Project: spring4-understanding   Source File: FrameworkServlet.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null) {
			Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
					"Could not add context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (Exception ex) {
		throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example 4
Source Project: spring-analysis-note   Source File: ContextLoader.java    License: MIT License 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example 5
/**
 * Resolve the set of merged {@code ApplicationContextInitializer} classes for the
 * supplied list of {@code ContextConfigurationAttributes}.
 * <p>Note that the {@link ContextConfiguration#inheritInitializers inheritInitializers}
 * flag of {@link ContextConfiguration @ContextConfiguration} will be taken into
 * consideration. Specifically, if the {@code inheritInitializers} flag is set to
 * {@code true} for a given level in the class hierarchy represented by the provided
 * configuration attributes, context initializer classes defined at the given level
 * will be merged with those defined in higher levels of the class hierarchy.
 * @param configAttributesList the list of configuration attributes to process; must
 * not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
 * (i.e., as if we were traversing up the class hierarchy)
 * @return the set of merged context initializer classes, including those from
 * superclasses if appropriate (never {@code null})
 * @since 3.2
 */
static Set<Class<? extends ApplicationContextInitializer<?>>> resolveInitializerClasses(
		List<ContextConfigurationAttributes> configAttributesList) {

	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes List must not be empty");
	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses = new LinkedHashSet<>();

	for (ContextConfigurationAttributes configAttributes : configAttributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace("Processing context initializers for configuration attributes " + configAttributes);
		}
		Collections.addAll(initializerClasses, configAttributes.getInitializers());
		if (!configAttributes.isInheritInitializers()) {
			break;
		}
	}

	return initializerClasses;
}
 
Example 6
@Test
public void hashCodeWithDifferentInitializers() {
	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses1 =
			new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
	initializerClasses1.add(FooInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses2 =
			new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
	initializerClasses2.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
 
Example 7
@Test
public void equalsWithDifferentInitializers() {
	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses1 =
			new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
	initializerClasses1.add(FooInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses2 =
			new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
	initializerClasses2.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertNotEquals(mergedConfig1, mergedConfig2);
	assertNotEquals(mergedConfig2, mergedConfig1);
}
 
Example 8
@Test
public void responseBodyAsHtmlWithSuffixPresent() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean();
			factoryBean.afterPropertiesSet();
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("contentNegotiationManager", factoryBean.getObject());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, TextRestController.class);

	byte[] content = "alert('boo')".getBytes(Charset.forName("ISO-8859-1"));
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/a2.html");
	request.setContent(content);
	MockHttpServletResponse response = new MockHttpServletResponse();

	getServlet().service(request, response);

	assertEquals(200, response.getStatus());
	assertEquals("text/html", response.getContentType());
	assertNull(response.getHeader("Content-Disposition"));
	assertArrayEquals(content, response.getContentAsByteArray());
}
 
Example 9
@Test
public void formController() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
		}
	}, MyFormController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("name", "name1");
	request.addParameter("age", "value2");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
 
Example 10
void assertMergedConfig(
		MergedContextConfiguration mergedConfig,
		Class<?> expectedTestClass,
		String[] expectedLocations,
		Class<?>[] expectedClasses,
		Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> expectedInitializerClasses,
		Class<? extends ContextLoader> expectedContextLoaderClass) {

	assertNotNull(mergedConfig);
	assertEquals(expectedTestClass, mergedConfig.getTestClass());
	assertNotNull(mergedConfig.getLocations());
	assertArrayEquals(expectedLocations, mergedConfig.getLocations());
	assertNotNull(mergedConfig.getClasses());
	assertArrayEquals(expectedClasses, mergedConfig.getClasses());
	assertNotNull(mergedConfig.getActiveProfiles());
	if (expectedContextLoaderClass == null) {
		assertNull(mergedConfig.getContextLoader());
	}
	else {
		assertEquals(expectedContextLoaderClass, mergedConfig.getContextLoader().getClass());
	}
	assertNotNull(mergedConfig.getContextInitializerClasses());
	assertEquals(expectedInitializerClasses, mergedConfig.getContextInitializerClasses());
}
 
Example 11
@Test
public void hashCodeWithDifferentInitializers() {
	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses1 =
			new HashSet<>();
	initializerClasses1.add(FooInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses2 =
			new HashSet<>();
	initializerClasses2.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
 
Example 12
@Test
public void responseBodyAsTextWithCssExtension() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean();
			factoryBean.afterPropertiesSet();
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("contentNegotiationManager", factoryBean.getObject());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, TextRestController.class);

	byte[] content = "body".getBytes(Charset.forName("ISO-8859-1"));
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/a4.css");
	request.setContent(content);
	MockHttpServletResponse response = new MockHttpServletResponse();

	getServlet().service(request, response);

	assertEquals(200, response.getStatus());
	assertEquals("text/css", response.getContentType());
	assertNull(response.getHeader("Content-Disposition"));
	assertArrayEquals(content, response.getContentAsByteArray());
}
 
Example 13
@Test
public void proxiedFormController() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory()
					.registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));
		}
	}, MyFormController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("name", "name1");
	request.addParameter("age", "value2");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
 
Example 14
@Test
public void pathVarsInModel() throws Exception {
	final Map<String, Object> pathVars = new HashMap<String, Object>();
	pathVars.put("hotel", "42");
	pathVars.put("booking", 21);
	pathVars.put("other", "other");

	WebApplicationContext wac =
		initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
			@Override
			public void initialize(GenericWebApplicationContext context) {
				RootBeanDefinition beanDef = new RootBeanDefinition(ModelValidatingViewResolver.class);
				beanDef.getConstructorArgumentValues().addGenericArgumentValue(pathVars);
				context.registerBeanDefinition("viewResolver", beanDef);
			}
		}, ViewRenderingController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=1,2/bookings/21-other;q=3;r=R");
	getServlet().service(request, new MockHttpServletResponse());

	ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class);
	assertEquals(3, resolver.validatedAttrCount);
}
 
Example 15
@Test
public void binderInitializingCommandProvidingFormController() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
		}
	}, MyBinderInitializingCommandProvidingFormController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("defaultName", "myDefaultName");
	request.addParameter("age", "value2");
	request.addParameter("date", "2007-10-02");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
 
Example 16
Source Project: spring-cloud-deployer-yarn   Source File: AppDeployerIT.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public YarnCloudAppService yarnCloudAppService() {
	ApplicationContextInitializer<?>[] initializers = new ApplicationContextInitializer<?>[] {
			new HadoopConfigurationInjectingInitializer(configuration) };
	String deployerVersion = environment.getProperty("projectVersion");
	return new DefaultYarnCloudAppService(deployerVersion, initializers) {
		@Override
		protected List<String> processContextRunArgs(List<String> contextRunArgs) {
			List<String> newArgs = new ArrayList<>();
			if (contextRunArgs != null) {
				newArgs.addAll(contextRunArgs);
			}
			newArgs.add("--deployer.yarn.app.appmaster.path=target/spring-cloud-deployer-yarn-build-tests");
			return newArgs;
		}
	};

}
 
Example 17
@Test
public void hashCodeWithSameInitializers() {
	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses1 =
			new HashSet<>();
	initializerClasses1.add(FooInitializer.class);
	initializerClasses1.add(BarInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses2 =
			new HashSet<>();
	initializerClasses2.add(BarInitializer.class);
	initializerClasses2.add(FooInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
 
Example 18
@Test
public void hashCodeWithDifferentInitializers() {
	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses1 =
			new HashSet<>();
	initializerClasses1.add(FooInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses2 =
			new HashSet<>();
	initializerClasses2.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
 
Example 19
Source Project: lams   Source File: FrameworkServlet.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example 20
@Test
public void equalsWithDifferentInitializers() {
	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses1 =
			new HashSet<>();
	initializerClasses1.add(FooInitializer.class);

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses2 =
			new HashSet<>();
	initializerClasses2.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
	MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
			EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
	assertNotEquals(mergedConfig1, mergedConfig2);
	assertNotEquals(mergedConfig2, mergedConfig1);
}
 
Example 21
@Bean
public ApplicationContextInitializer<ConfigurableApplicationContext> customInitializer() {
	return new ApplicationContextInitializer<ConfigurableApplicationContext>() {

		@Override
		public void initialize(ConfigurableApplicationContext applicationContext) {
			ConfigurableEnvironment environment = applicationContext.getEnvironment();
			environment.getPropertySources()
					.addLast(new MapPropertySource("customProperties",
							Collections.<String, Object>singletonMap("custom.foo",
									environment.resolvePlaceholders(
											"${spring.application.name:bar}"))));
		}

	};
}
 
Example 22
Source Project: lams   Source File: ContextLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example 23
Source Project: spring-cloud-deployer-yarn   Source File: TaskLauncherIT.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public YarnCloudAppService yarnCloudAppService() {
	ApplicationContextInitializer<?>[] initializers = new ApplicationContextInitializer<?>[] {
			new HadoopConfigurationInjectingInitializer(configuration) };
	String deployerVersion = environment.getProperty("projectVersion");
	return new DefaultYarnCloudAppService(deployerVersion, initializers) {
		@Override
		protected List<String> processContextRunArgs(List<String> contextRunArgs) {
			List<String> newArgs = new ArrayList<>();
			if (contextRunArgs != null) {
				newArgs.addAll(contextRunArgs);
			}
			newArgs.add("--deployer.yarn.app.appmaster.path=target/spring-cloud-deployer-yarn-build-tests");
			return newArgs;
		}
	};
}
 
Example 24
@Test
public void responseBodyAsHtml() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean();
			factoryBean.afterPropertiesSet();
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("contentNegotiationManager", factoryBean.getObject());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, TextRestController.class);

	byte[] content = "alert('boo')".getBytes(Charset.forName("ISO-8859-1"));
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/a1.html");
	request.setContent(content);
	MockHttpServletResponse response = new MockHttpServletResponse();

	getServlet().service(request, response);

	assertEquals(200, response.getStatus());
	assertEquals("text/html", response.getContentType());
	assertEquals("inline;filename=f.txt", response.getHeader("Content-Disposition"));
	assertArrayEquals(content, response.getContentAsByteArray());
}
 
Example 25
Source Project: spring-init   Source File: FunctionalInstallerListener.java    License: Apache License 2.0 6 votes vote down vote up
private void findInitializers(SpringApplication application) {
	for (Object source : application.getAllSources()) {
		if (source instanceof Class<?>) {
			Class<?> type = (Class<?>) source;
			String cls = type.getName().replace("$", "_") + "Initializer";
			if (ClassUtils.isPresent(cls, application.getClassLoader())) {
				@SuppressWarnings("unchecked")
				Class<? extends ApplicationContextInitializer<?>> initializer = (Class<? extends ApplicationContextInitializer<?>>) ClassUtils
						.resolveClassName(cls, application.getClassLoader());
				addInitializer(initializer);
				remove(application, source);
			}
		}
	}
	if (application.getAllSources().isEmpty()) {
		// Spring Boot is fussy and doesn't like to run with no sources
		application.addPrimarySources(Arrays.asList(Object.class));
	}
}
 
Example 26
@Test
public void typeNestedSetBinding() throws Exception {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext context) {
			RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class);
			csDef.getPropertyValues().add("converters", new TestBeanConverter());
			RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class);
			wbiDef.getPropertyValues().add("conversionService", csDef);
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef);
			context.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, NestedSetController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("testBeanSet", new String[] {"1", "2"});
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString());
}
 
Example 27
Source Project: spring-analysis-note   Source File: ContextLoader.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Class<ApplicationContextInitializer<ConfigurableApplicationContext>> loadInitializerClass(String className) {
	try {
		Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
		if (!ApplicationContextInitializer.class.isAssignableFrom(clazz)) {
			throw new ApplicationContextException(
					"Initializer class does not implement ApplicationContextInitializer interface: " + clazz);
		}
		return (Class<ApplicationContextInitializer<ConfigurableApplicationContext>>) clazz;
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException("Failed to load context initializer class [" + className + "]", ex);
	}
}
 
Example 28
@SuppressWarnings("unchecked")
private void create(
		Class<? extends ApplicationContextInitializer<GenericApplicationContext>> type,
		String... props) {
	create(Arrays.asList(BeanUtils.instantiateClass(type))
			.toArray(new ApplicationContextInitializer[0]), props);
}
 
Example 29
Source Project: spring-analysis-note   Source File: AbstractContextLoader.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
		MergedContextConfiguration mergedConfig) {

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses =
			mergedConfig.getContextInitializerClasses();
	if (initializerClasses.isEmpty()) {
		// no ApplicationContextInitializers have been declared -> nothing to do
		return;
	}

	List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<>();
	Class<?> contextClass = context.getClass();

	for (Class<? extends ApplicationContextInitializer<?>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(context)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					contextClass.getName()));
		}
		initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(initializerInstances);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
		initializer.initialize(context);
	}
}
 
Example 30
@Test
public void buildMergedConfigWithOverriddenInitializersAndClasses() {
	Class<?> testClass = OverriddenInitializersAndClassesBar.class;
	Class<?>[] expectedClasses = new Class<?>[] { BarConfig.class };
	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> expectedInitializerClasses//
	= new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
	expectedInitializerClasses.add(BarInitializer.class);

	MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass);

	assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, expectedInitializerClasses,
		DelegatingSmartContextLoader.class);
}