org.springframework.context.ApplicationContextInitializer Java Examples

The following examples show how to use org.springframework.context.ApplicationContextInitializer. 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: MergedContextConfigurationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #2
Source File: MergedContextConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: ContextLoader.java    From spring-analysis-note with 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
Source File: MergedContextConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: FrameworkServlet.java    From spring4-understanding with 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 #7
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: FunctionalInstallerListener.java    From spring-init with 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 #9
Source File: ApplicationContextInitializerUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 #10
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: AbstractContextConfigurationUtilsTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: TaskLauncherIT.java    From spring-cloud-deployer-yarn with 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 #15
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: MergedContextConfigurationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #17
Source File: AppDeployerIT.java    From spring-cloud-deployer-yarn with 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 #18
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: FrameworkServlet.java    From lams with 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
Source File: UriTemplateServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #21
Source File: MergedContextConfigurationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #22
Source File: TestBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@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 #23
Source File: ContextLoader.java    From lams with 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 #24
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #25
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #26
Source File: MergedContextConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #27
Source File: ContextLoader.java    From spring-analysis-note with 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
Source File: ContextLoader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Specify which {@link ApplicationContextInitializer} instances should be used
 * to initialize the application context used by this {@code ContextLoader}.
 * @since 4.2
 * @see #configureAndRefreshWebApplicationContext
 * @see #customizeContext
 */
@SuppressWarnings("unchecked")
public void setContextInitializers(@Nullable ApplicationContextInitializer<?>... initializers) {
	if (initializers != null) {
		for (ApplicationContextInitializer<?> initializer : initializers) {
			this.contextInitializers.add((ApplicationContextInitializer<ConfigurableApplicationContext>) initializer);
		}
	}
}
 
Example #29
Source File: ContextLoader.java    From lams with GNU General Public License v2.0 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 #30
Source File: MSF4JSpringApplication.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private void applyInitializers(ConfigurableApplicationContext context) {
    for (ApplicationContextInitializer initializer : getInitializers()) {
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
                initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context);
    }
}