org.springframework.context.ConfigurableApplicationContext Java Examples

The following examples show how to use org.springframework.context.ConfigurableApplicationContext. 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: AbstractUnitTest.java    From event-sourcing-microservices-example with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void initialize(@NotNull ConfigurableApplicationContext configurableApplicationContext) {
	String jdbcUrl = String.format("jdbc:postgresql://%s:%d/%s", postgres.getContainerIpAddress(),
			postgres.getMappedPort(5432), "postgres");

	TestPropertyValues values = TestPropertyValues.of(
			"postgres.host=" + postgres.getContainerIpAddress(),
			"postgres.port=" + postgres.getMappedPort(5432),
			"postgres.url=" + jdbcUrl,
			"postgres.database-name=postgres",
			"spring.application.name=user-service",
			"spring.datasource.data-username=postgres",
			"spring.datasource.data-password=password",
			"spring.datasource.url=" + jdbcUrl,
			"eureka.client.enabled=false");

	values.applyTo(configurableApplicationContext);
}
 
Example #2
Source File: ApplicationContextInitializerUtils.java    From spring4-understanding with Apache License 2.0 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<? extends ConfigurableApplicationContext>>> resolveInitializerClasses(
		List<ContextConfigurationAttributes> configAttributesList) {
	Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");

	final Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = //
	new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();

	for (ContextConfigurationAttributes configAttributes : configAttributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing context initializers for context configuration attributes %s",
				configAttributes));
		}

		initializerClasses.addAll(Arrays.asList(configAttributes.getInitializers()));

		if (!configAttributes.isInheritInitializers()) {
			break;
		}
	}

	return initializerClasses;
}
 
Example #3
Source File: BeanFactoryPostProcessorBootstrap.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("factory.bean/factory-post-processor.xml");
	BeanFactoryPostProcessor beanFactoryPostProcessor = (BeanFactoryPostProcessor) context.getBean("carPostProcessor");
	beanFactoryPostProcessor.postProcessBeanFactory(context.getBeanFactory());
	// 输出 :Car{maxSpeed=0, brand='*****', price=10000.0},敏感词被替换了
	System.out.println(context.getBean("car"));

	// 硬编码 后处理器执行时间
	BeanFactoryPostProcessor hardCodeBeanFactoryPostProcessor = new HardCodeBeanFactoryPostProcessor();
	context.addBeanFactoryPostProcessor(hardCodeBeanFactoryPostProcessor);
	// 更新上下文
	context.refresh();
	// 输出 :
	// Hard Code BeanFactory Post Processor execute time
	// Car{maxSpeed=0, brand='*****', price=10000.0}
	System.out.println(context.getBean("car"));
}
 
Example #4
Source File: SpringCustomizedPropertyEditorDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 创建并且启动 BeanFactory 容器,
    ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/property-editors-context.xml");

    // AbstractApplicationContext -> "conversionService" ConversionService Bean
    // -> ConfigurableBeanFactory#setConversionService(ConversionService)
    // -> AbstractAutowireCapableBeanFactory.instantiateBean
    // -> AbstractBeanFactory#getConversionService ->
    // BeanDefinition -> BeanWrapper -> 属性转换(数据来源:PropertyValues)->
    // setPropertyValues(PropertyValues) -> TypeConverter#convertIfNecessnary
    // TypeConverterDelegate#convertIfNecessnary  -> PropertyEditor or ConversionService

    User user = applicationContext.getBean("user", User.class);

    System.out.println(user);

    // 显示地关闭 Spring 应用上下文
    applicationContext.close();
}
 
Example #5
Source File: MsgsServerApplication.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws UnknownHostException {
    ConfigurableApplicationContext application = SpringApplication.run(MsgsServerApplication.class, args);
    Environment env = application.getEnvironment();
    log.info("\n----------------------------------------------------------\n\t" +
                    "应用 '{}' 运行成功! 访问连接:\n\t" +
                    "Swagger文档: \t\thttp://{}:{}/doc.html\n\t" +
                    "数据库监控: \t\thttp://{}:{}/druid\n" +
                    "----------------------------------------------------------",
            env.getProperty("spring.application.name"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port")

    );
}
 
Example #6
Source File: BootstrapApplicationListener.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void addAncestorInitializer(SpringApplication application,
		ConfigurableApplicationContext context) {
	boolean installed = false;
	for (ApplicationContextInitializer<?> initializer : application
			.getInitializers()) {
		if (initializer instanceof AncestorInitializer) {
			installed = true;
			// New parent
			((AncestorInitializer) initializer).setParent(context);
		}
	}
	if (!installed) {
		application.addInitializers(new AncestorInitializer(context));
	}

}
 
Example #7
Source File: ContentTypeTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendBynaryData() throws Exception {
	try (ConfigurableApplicationContext context = SpringApplication.run(
			SourceApplication.class, "--server.port=0",
			"--spring.jmx.enabled=false")) {

		MessageCollector collector = context.getBean(MessageCollector.class);
		Source source = context.getBean(Source.class);
		byte[] data = new byte[] { 0, 1, 2, 3 };
		source.output()
				.send(MessageBuilder.withPayload(data)
						.setHeader(MessageHeaders.CONTENT_TYPE,
								MimeTypeUtils.APPLICATION_OCTET_STREAM)
						.build());
		Message<byte[]> message = (Message<byte[]>) collector
				.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
		assertThat(
				message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
						.includes(MimeTypeUtils.APPLICATION_OCTET_STREAM));
		assertThat(message.getPayload()).isEqualTo(data);
	}
}
 
Example #8
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleFunctionWithNativeProperty() {

	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(NoEnableBindingConfiguration.class))
					.web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false", "--spring.cloud.function.definition=func")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());

	}
}
 
Example #9
Source File: SpringBatchFlowRunner.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
SpringBatchFlowRunner(StepBuilderFactory stepBuilderFactory,
		JobBuilderFactory jobBuilderFactory,
		ProjectsToRunFactory projectsToRunFactory, JobLauncher jobLauncher,
		FlowRunnerTaskExecutorSupplier flowRunnerTaskExecutorSupplier,
		ConfigurableApplicationContext context, ReleaserProperties releaserProperties,
		BuildReportHandler reportHandler) {
	this.stepBuilderFactory = stepBuilderFactory;
	this.jobBuilderFactory = jobBuilderFactory;
	this.projectsToRunFactory = projectsToRunFactory;
	this.jobLauncher = jobLauncher;
	this.flowRunnerTaskExecutorSupplier = flowRunnerTaskExecutorSupplier;
	this.stepSkipper = new ConsoleInputStepSkipper(context, reportHandler);
	this.releaserProperties = releaserProperties;
	this.executorService = Executors.newFixedThreadPool(
			this.releaserProperties.getMetaRelease().getReleaseGroupThreadCount());
}
 
Example #10
Source File: DemoApplication.java    From springboot_security_restful_api with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    ConfigurableApplicationContext context =
        SpringApplication.run(DemoApplication.class, args);
    UserRepository userRepository = context.getBean(UserRepository.class);
    AuthorityRepository authorityRepository = context.getBean(AuthorityRepository.class);

    Authority adminAuthority = getOrGreateAuthority("ROLE_ADMIN", authorityRepository);
    Authority basicAuthority = getOrGreateAuthority("ROLE_BASIC", authorityRepository);

    User admin = new User("admin", "123456");
    encodePassword(admin);
    admin.getAuthorities().add(adminAuthority);
    admin.getAuthorities().add(basicAuthority);

    User test = new User("test", "test");
    encodePassword(test);
    test.getAuthorities().add(basicAuthority);

    userRepository.save(admin);
    userRepository.save(test);
}
 
Example #11
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithExplicitBindingInstructionsOnlyDestination() {
	System.clearProperty("spring.cloud.function.definition");
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestChannelBinderConfiguration
			.getCompleteConfiguration(SplittableTypesConfiguration.class))
					.web(WebApplicationType.NONE).run(
							"--spring.cloud.function.definition=funcArrayOfMessages",
							"--spring.cloud.stream.bindings.funcArrayOfMessages-in-0.destination=myInput",
							"--spring.cloud.stream.bindings.funcArrayOfMessages-out-0.destination=myOutput",
							"--spring.jmx.enabled=false")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("aa,bb,cc,dd".getBytes()).build();

		inputDestination.send(inputMessage, "myInput");

		assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("aa");
		assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("bb");
		assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("cc");
		assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("dd");
		assertThat(outputDestination.receive(100)).isNull();
	}
}
 
Example #12
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 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 #13
Source File: ContextHierarchyDirtiesContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void runTestAndVerifyHierarchies(Class<? extends FooTestCase> testClass, boolean isFooContextActive,
		boolean isBarContextActive, boolean isBazContextActive) {

	JUnitCore jUnitCore = new JUnitCore();
	Result result = jUnitCore.run(testClass);
	assertTrue("all tests passed", result.wasSuccessful());

	assertThat(ContextHierarchyDirtiesContextTests.context, notNullValue());

	ConfigurableApplicationContext bazContext = (ConfigurableApplicationContext) ContextHierarchyDirtiesContextTests.context;
	assertEquals("baz", ContextHierarchyDirtiesContextTests.baz);
	assertThat("bazContext#isActive()", bazContext.isActive(), is(isBazContextActive));

	ConfigurableApplicationContext barContext = (ConfigurableApplicationContext) bazContext.getParent();
	assertThat(barContext, notNullValue());
	assertEquals("bar", ContextHierarchyDirtiesContextTests.bar);
	assertThat("barContext#isActive()", barContext.isActive(), is(isBarContextActive));

	ConfigurableApplicationContext fooContext = (ConfigurableApplicationContext) barContext.getParent();
	assertThat(fooContext, notNullValue());
	assertEquals("foo", ContextHierarchyDirtiesContextTests.foo);
	assertThat("fooContext#isActive()", fooContext.isActive(), is(isFooContextActive));
}
 
Example #14
Source File: MiCommonApplication.java    From MI-S with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	ConfigurableApplicationContext context =  SpringApplication.run(MiCommonApplication.class, args);
	String[] activeProfiles = context.getEnvironment().getActiveProfiles();
	for (String profile : activeProfiles){
		log.info("String active profile:{}" ,profile);
	}
	log.info("应用程序启动完毕");
}
 
Example #15
Source File: QueueMessageHandler.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private String[] resolveName(String name) {
	if (!(getApplicationContext() instanceof ConfigurableApplicationContext)) {
		return wrapInStringArray(name);
	}

	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) getApplicationContext();
	ConfigurableBeanFactory configurableBeanFactory = applicationContext
			.getBeanFactory();

	String placeholdersResolved = configurableBeanFactory.resolveEmbeddedValue(name);
	BeanExpressionResolver exprResolver = configurableBeanFactory
			.getBeanExpressionResolver();
	if (exprResolver == null) {
		return wrapInStringArray(name);
	}
	Object result = exprResolver.evaluate(placeholdersResolved,
			new BeanExpressionContext(configurableBeanFactory, null));
	if (result instanceof String[]) {
		return (String[]) result;
	}
	else if (result != null) {
		return wrapInStringArray(result);
	}
	else {
		return wrapInStringArray(name);
	}
}
 
Example #16
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Close the WebApplicationContext of this servlet.
 * @see org.springframework.context.ConfigurableApplicationContext#close()
 */
@Override
public void destroy() {
	getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'");
	// Only call close() on WebApplicationContext if locally managed...
	if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
		((ConfigurableApplicationContext) this.webApplicationContext).close();
	}
}
 
Example #17
Source File: PropertyMaskingContextInitializer.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example #18
Source File: ClientCachePoolCustomizationsIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private void testNamedPoolWasNotCustomized(ConfigurableApplicationContext applicationContext, String poolName, boolean poolBeanPresent) {

		try {
			testNamedPoolWasCustomized(applicationContext, poolName, poolBeanPresent);
			fail("Pool [%s] should not have been modified", poolName);
		}
		catch (Throwable ignore) { }
	}
 
Example #19
Source File: JCacheJavaConfigTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void bothSetOnlyResolverIsUsed() {
	ConfigurableApplicationContext context =
			new AnnotationConfigApplicationContext(FullCachingConfigSupport.class);

	DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class);
	assertSame(context.getBean("cacheResolver"), cos.getCacheResolver());
	assertSame(context.getBean("keyGenerator"), cos.getKeyGenerator());
	assertSame(context.getBean("exceptionCacheResolver"), cos.getExceptionCacheResolver());
	context.close();
}
 
Example #20
Source File: DiscoveryClientRegistrationInvoker.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ConfigurableApplicationContext context) {
    if(context instanceof ServletWebServerApplicationContext
            && !AdminEndpointApplicationRunListener.isEmbeddedServletServer(context.getEnvironment())) {
        MetaDataProvider metaDataProvider = context.getBean(MetaDataProvider.class);
        WebServer webServer = new WebServer() {
            @Override
            public void start() throws WebServerException {

            }

            @Override
            public void stop() throws WebServerException {

            }

            @Override
            public int getPort() {
                return metaDataProvider.getServerPort();
            }
        };
        context.publishEvent(
                new ServletWebServerInitializedEvent(
                        webServer,
                        new ServletWebServerApplicationContext())
        );
    }
}
 
Example #21
Source File: AnnotationNamespaceDrivenTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cacheResolver() {
	ConfigurableApplicationContext context = new GenericXmlApplicationContext(
			"/org/springframework/cache/config/annotationDrivenCacheNamespace-resolver.xml");

	CacheInterceptor ci = context.getBean(CacheInterceptor.class);
	assertSame(context.getBean("cacheResolver"), ci.getCacheResolver());
	context.close();
}
 
Example #22
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the type of Spring {@link ApplicationContext} that will be created. If not
 * specified defaults to {@link #DEFAULT_WEB_CONTEXT_CLASS} for web based applications
 * or {@link AnnotationConfigApplicationContext} for non web based applications.
 * @param applicationContextClass the context class to set
 */
public void setApplicationContextClass(
		Class<? extends ConfigurableApplicationContext> applicationContextClass) {
	this.applicationContextClass = applicationContextClass;
	if (!isWebApplicationContext(applicationContextClass)) {
		this.webApplicationType = WebApplicationType.NONE;
	}
}
 
Example #23
Source File: RecommendationServiceApplication.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	ConfigurableApplicationContext ctx = SpringApplication.run(RecommendationServiceApplication.class, args);

	String mongodDbHost = ctx.getEnvironment().getProperty("spring.data.mongodb.host");
	String mongodDbPort = ctx.getEnvironment().getProperty("spring.data.mongodb.port");
	LOG.info("Connected to MongoDb: " + mongodDbHost + ":" + mongodDbPort);
}
 
Example #24
Source File: KafkaStreamsBinderHealthIndicatorTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
private static void checkHealth(ConfigurableApplicationContext context,
		Status expected) throws InterruptedException {
	CompositeHealthContributor healthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);
	KafkaStreamsBinderHealthIndicator kafkaStreamsBinderHealthIndicator = (KafkaStreamsBinderHealthIndicator) healthIndicator.getContributor("kstream");
	Health health = kafkaStreamsBinderHealthIndicator.health();
	while (waitFor(health.getStatus(), health.getDetails())) {
		TimeUnit.SECONDS.sleep(2);
		health = kafkaStreamsBinderHealthIndicator.health();
	}
	assertThat(health.getStatus()).isEqualTo(expected);
}
 
Example #25
Source File: PropertyMaskingContextInitializer.java    From spring-cloud-services-connector with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example #26
Source File: AbstractInstancesProxyControllerIntegrationTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
protected void setUpClient(ConfigurableApplicationContext context) {
	int localPort = context.getEnvironment().getProperty("local.server.port", Integer.class, 0);
	this.client = WebTestClient.bindToServer().baseUrl("http://localhost:" + localPort)
			.responseTimeout(Duration.ofSeconds(10)).build();

	this.instanceId = registerInstance("/instance1");
}
 
Example #27
Source File: SourceToFunctionsSupportTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testImperativeSupplierComposedWithFunctions() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					FunctionsConfiguration.class, SupplierConfiguration.class)).web(WebApplicationType.NONE).run(
							"--spring.cloud.stream.function.definition=number|toUpperCase|concatWithSelf",
							"--spring.jmx.enabled=false")) {

		OutputDestination target = context.getBean(OutputDestination.class);
		String result = new String(target.receive(1000).getPayload(), StandardCharsets.UTF_8);
		assertThat(result).isEqualTo("1:1");
	}
}
 
Example #28
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void genericApplicationContext_standardEnv() {
	ConfigurableApplicationContext ctx = new GenericApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
	ctx.refresh();

	assertHasStandardEnvironment(ctx);
	assertEnvironmentBeanRegistered(ctx);
	assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
}
 
Example #29
Source File: CypherLoaderIT.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSpringMultiConfig ()
{
	try ( 
		ConfigurableApplicationContext beanCtx = new ClassPathXmlApplicationContext ( "multi_config.xml" );
		MultiConfigCyLoader mloader = MultiConfigCyLoader.getSpringInstance ( beanCtx );				
	)
	{			
		mloader.load ( RdfDataManagerTest.TDB_PATH );
		// TODO: test
	}
}
 
Example #30
Source File: FunctionalConfigurationPropertiesBinder.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
public FunctionalConfigurationPropertiesBinder(ConfigurableApplicationContext context) {
	PropertySources propertySources = new FunctionalPropertySourcesDeducer(context).getPropertySources();
	this.context = context;
	this.binder = new Binder(ConfigurationPropertySources.from(propertySources),
       				new PropertySourcesPlaceholdersResolver(propertySources),
       				null,
			(registry) -> context.getBeanFactory().copyRegisteredEditorsTo(registry));
}