org.springframework.context.ConfigurableApplicationContext#setEnvironment ( )源码实例Demo

下面列出了org.springframework.context.ConfigurableApplicationContext#setEnvironment ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void fileSystemXmlApplicationContext() throws IOException {
	ClassPathResource xml = new ClassPathResource(XML_PATH);
	File tmpFile = File.createTempFile("test", "xml");
	FileCopyUtils.copy(xml.getFile(), tmpFile);

	// strange - FSXAC strips leading '/' unless prefixed with 'file:'
	ConfigurableApplicationContext ctx =
			new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();
	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
@Test
public void fileSystemXmlApplicationContext() throws IOException {
	ClassPathResource xml = new ClassPathResource(XML_PATH);
	File tmpFile = File.createTempFile("test", "xml");
	FileCopyUtils.copy(xml.getFile(), tmpFile);

	// strange - FSXAC strips leading '/' unless prefixed with 'file:'
	ConfigurableApplicationContext ctx =
			new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();
	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
源代码3 项目: spring-javaformat   文件: SpringApplication.java
private void prepareContext(ConfigurableApplicationContext context,
		ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
		ApplicationArguments applicationArguments, Banner printedBanner) {
	context.setEnvironment(environment);
	postProcessApplicationContext(context);
	applyInitializers(context);
	listeners.contextPrepared(context);
	if (this.logStartupInfo) {
		logStartupInfo(context.getParent() == null);
		logStartupProfileInfo(context);
	}

	// Add boot specific singleton beans
	context.getBeanFactory().registerSingleton("springApplicationArguments",
			applicationArguments);
	if (printedBanner != null) {
		context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
	}

	// Load the sources
	Set<Object> sources = getAllSources();
	Assert.notEmpty(sources, "Sources must not be empty");
	load(context, sources.toArray(new Object[0]));
	listeners.contextLoaded(context);
}
 
@Test
public void fileSystemXmlApplicationContext() throws IOException {
	ClassPathResource xml = new ClassPathResource(XML_PATH);
	File tmpFile = File.createTempFile("test", "xml");
	FileCopyUtils.copy(xml.getFile(), tmpFile);

	// strange - FSXAC strips leading '/' unless prefixed with 'file:'
	ConfigurableApplicationContext ctx =
			new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();
	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
@Test
public void classPathXmlApplicationContext() {
	ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(XML_PATH);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();

	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
@Test
public void classPathXmlApplicationContext() {
	ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(XML_PATH);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();

	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
源代码7 项目: netstrap   文件: NetstrapBootApplication.java
/**
 * 装配SpringContext
 * 设置环境,初始化调用,设置监听器
 */
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment) {
    context.setEnvironment(environment);
    applyInitializer(context);
    for (ApplicationListener listener : listeners) {
        context.addApplicationListener(listener);
    }
}
 
@Test
public void classPathXmlApplicationContext() {
	ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(XML_PATH);
	ctx.setEnvironment(prodEnv);
	ctx.refresh();

	assertEnvironmentBeanRegistered(ctx);
	assertHasEnvironment(ctx, prodEnv);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("admin.api.url", "/admin");
    environment.setProperty("admin.i18n.path", "/admin/i18n");
    environment.setProperty("admin.debug", "true");
    applicationContext.setEnvironment(environment);
}
 
@SuppressWarnings("rawtypes")
@Bean
public Binder<?, ?, ?> extendedPropertiesBinder() {
	Binder mock = Mockito.mock(Binder.class,
			Mockito.withSettings().defaultAnswer(Mockito.RETURNS_MOCKS)
					.extraInterfaces(ExtendedPropertiesBinder.class));
	ConfigurableEnvironment environment = new StandardEnvironment();
	Map<String, Object> propertiesToAdd = new HashMap<>();
	propertiesToAdd.put("spring.cloud.stream.foo.default.consumer.extendedProperty",
			"someFancyExtension");
	propertiesToAdd.put("spring.cloud.stream.foo.default.producer.extendedProperty",
			"someFancyExtension");
	environment.getPropertySources()
			.addLast(new MapPropertySource("extPropertiesConfig", propertiesToAdd));

	ConfigurableApplicationContext applicationContext = new GenericApplicationContext();
	applicationContext.setEnvironment(environment);

	FooExtendedBindingProperties fooExtendedBindingProperties = new FooExtendedBindingProperties();
	fooExtendedBindingProperties.setApplicationContext(applicationContext);

	final FooConsumerProperties fooConsumerProperties = fooExtendedBindingProperties
			.getExtendedConsumerProperties("input");
	final FooProducerProperties fooProducerProperties = fooExtendedBindingProperties
			.getExtendedProducerProperties("output");

	when(((ExtendedPropertiesBinder) mock).getExtendedConsumerProperties("input"))
			.thenReturn(fooConsumerProperties);

	when(((ExtendedPropertiesBinder) mock).getExtendedProducerProperties("output"))
			.thenReturn(fooProducerProperties);

	return mock;
}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();

	String[] defaultKeys = {"password", "secret", "key", "token", ".*credentials.*", "vcap_services"};
	Set<String> propertiesToSanitize = Stream.of(defaultKeys)
											 .collect(Collectors.toSet());

	PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
	Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
	Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();

	if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
		bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
	}
	for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
		if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
			configServiceNestedPropertySources.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
		}
	}

	Stream<String> vaultKeyNameStream =
			configServiceNestedPropertySources.stream()
											  .filter(ps -> ps instanceof EnumerablePropertySource)
											  .filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN) || ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
											  .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
											  .flatMap(Arrays::<String>stream);

	propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));

	PropertiesPropertySource envKeysToSanitize =
			new PropertiesPropertySource(
					SANITIZE_ENV_KEY, mergeClientProperties(propertySources, propertiesToSanitize));

	environment.getPropertySources().addFirst(envKeysToSanitize);
	applicationContext.setEnvironment(environment);

}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();

	String[] defaultKeys = { "password", "secret", "key", "token", ".*credentials.*", "vcap_services" };
	Set<String> propertiesToSanitize = Stream.of(defaultKeys).collect(Collectors.toSet());

	PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
	Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
	Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();

	if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
		bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
	}
	for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
		if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
			configServiceNestedPropertySources
					.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
		}
	}

	Stream<String> vaultKeyNameStream = configServiceNestedPropertySources.stream()
			.filter(ps -> ps instanceof EnumerablePropertySource)
			.filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN)
					|| ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::<String>stream);

	propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));

	PropertiesPropertySource envKeysToSanitize = new PropertiesPropertySource(SANITIZE_ENV_KEY,
			mergeClientProperties(propertySources, propertiesToSanitize));

	environment.getPropertySources().addFirst(envKeysToSanitize);
	applicationContext.setEnvironment(environment);

}