org.springframework.core.env.MutablePropertySources Java Examples

The following examples show how to use org.springframework.core.env.MutablePropertySources. 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: FunctionDeployerConfiguration.java    From spring-cloud-function with Apache License 2.0 7 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String functionName = environment.containsProperty("function.name") ? environment.getProperty("function.name") : null;
	String functionLocation = environment.containsProperty("function.location") ? environment.getProperty("function.location") : null;
	if (StringUtils.hasText(functionName) || StringUtils.hasText(functionLocation)) {
		MutablePropertySources propertySources = environment.getPropertySources();
		propertySources.forEach(ps -> {
			if (ps instanceof PropertiesPropertySource) {
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".definition", functionName);
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".location", functionLocation);
			}
		});
	}
}
 
Example #2
Source File: PropertySourceAnnotationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withExplicitName() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ConfigWithExplicitName.class);
	ctx.refresh();
	assertTrue("property source p1 was not added",
			ctx.getEnvironment().getPropertySources().contains("p1"));
	assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));

	// assert that the property source was added last to the set of sources
	String name;
	MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
	Iterator<org.springframework.core.env.PropertySource<?>> iterator = sources.iterator();
	do {
		name = iterator.next().getName();
	}
	while (iterator.hasNext());

	assertThat(name, is("p1"));
}
 
Example #3
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void explicitPropertySourcesExcludesEnvironment() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPropertySources(propertySources);
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env"));
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
	assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
}
 
Example #4
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void explicitPropertySourcesExcludesLocalProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPropertySources(propertySources);
	ppc.setProperties(new Properties() {{
		put("my.name", "local");
	}});
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
 
Example #5
Source File: EnvironmentConfigurationLogger.java    From pcf-crash-course-with-spring-boot with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	@EventListener
	public void handleContextRefresh(ContextRefreshedEvent event) {
		final Environment environment = event.getApplicationContext().getEnvironment();
		LOGGER.info("====== Environment and configuration ======");
		LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
		final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
		StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
				.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
				.forEach(prop -> {
					LOGGER.info("{}", prop);
//					Object resolved = environment.getProperty(prop, Object.class);
//					if (resolved instanceof String) {
//						LOGGER.info("{}", environment.getProperty(prop));
//					}
				});
		LOGGER.info("===========================================");
	}
 
Example #6
Source File: DispatcherWebscript.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
protected void configureDispatcherServlet(DispatcherServlet dispatcherServlet) {
	if (inheritGlobalProperties) {
		final Properties globalProperties = (Properties) this.applicationContext.getBean("global-properties");

		ConfigurableEnvironment servletEnv = dispatcherServlet.getEnvironment();
		servletEnv.merge(new AbstractEnvironment() {
			@Override
			public MutablePropertySources getPropertySources() {
				MutablePropertySources mutablePropertySources = new MutablePropertySources();
				mutablePropertySources
						.addFirst(new PropertiesPropertySource("alfresco-global.properties", globalProperties));
				return mutablePropertySources;
			}
		});
	}
}
 
Example #7
Source File: EnvironmentConfigurationLogger.java    From kubernetes-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
	final Environment environment = event.getApplicationContext().getEnvironment();
	LOGGER.info("====== Environment and configuration ======");
	LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
	final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
	StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
			.forEach(prop -> {
				Object resolved = environment.getProperty(prop, Object.class);
				if (resolved instanceof String) {
					LOGGER.info("{} - {}", prop, environment.getProperty(prop));
				} else {
					LOGGER.info("{} - {}", prop, "NON-STRING-VALUE");
				}
				
			});
	LOGGER.debug("===========================================");
}
 
Example #8
Source File: EnvironmentConfigurationLogger.java    From kubernetes-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
	final Environment environment = event.getApplicationContext().getEnvironment();
	LOGGER.info("====== Environment and configuration ======");
	LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
	final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
	StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
			.forEach(prop -> {
				Object resolved = environment.getProperty(prop, Object.class);
				if (resolved instanceof String) {
					LOGGER.info("{} - {}", prop, environment.getProperty(prop));
				} else {
					LOGGER.info("{} - {}", prop, "NON-STRING-VALUE");
				}
				
			});
	LOGGER.debug("===========================================");
}
 
Example #9
Source File: EnvironmentConfigurationLogger.java    From kubernetes-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
	final Environment environment = event.getApplicationContext().getEnvironment();
	LOGGER.info("====== Environment and configuration ======");
	LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
	final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
	StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
			.forEach(prop -> {
				Object resolved = environment.getProperty(prop, Object.class);
				if (resolved instanceof String) {
					LOGGER.info("{} - {}", prop, environment.getProperty(prop));
				} else {
					LOGGER.info("{} - {}", prop, "NON-STRING-VALUE");
				}
				
			});
	LOGGER.debug("===========================================");
}
 
Example #10
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void explicitPropertySourcesExcludesLocalProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer pc = new PropertySourcesPlaceholderConfigurer();
	pc.setPropertySources(propertySources);
	pc.setProperties(new Properties() {{
		put("my.name", "local");
	}});
	pc.setIgnoreUnresolvablePlaceholders(true);
	pc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
 
Example #11
Source File: BootstrapApplicationListener.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void mergeDefaultProperties(MutablePropertySources environment,
		MutablePropertySources bootstrap) {
	String name = DEFAULT_PROPERTIES;
	if (bootstrap.contains(name)) {
		PropertySource<?> source = bootstrap.get(name);
		if (!environment.contains(name)) {
			environment.addLast(source);
		}
		else {
			PropertySource<?> target = environment.get(name);
			if (target instanceof MapPropertySource && target != source
					&& source instanceof MapPropertySource) {
				Map<String, Object> targetMap = ((MapPropertySource) target)
						.getSource();
				Map<String, Object> map = ((MapPropertySource) source).getSource();
				for (String key : map.keySet()) {
					if (!target.containsProperty(key)) {
						targetMap.put(key, map.get(key));
					}
				}
			}
		}
	}
	mergeAdditionalPropertySources(environment, bootstrap);
}
 
Example #12
Source File: EnvironmentConfigurationLogger.java    From docker-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	@EventListener
	public void handleContextRefresh(ContextRefreshedEvent event) {
		final Environment environment = event.getApplicationContext().getEnvironment();
		LOGGER.debug("====== Environment and configuration ======");
		LOGGER.debug("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
		final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
		StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
				.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
				.forEach(prop -> {
					LOGGER.debug("{}", prop);
//					Object resolved = environment.getProperty(prop, Object.class);
//					if (resolved instanceof String) {
//						LOGGER.info("{}", environment.getProperty(prop));
//					}
				});
		LOGGER.debug("===========================================");
	}
 
Example #13
Source File: EnvironmentConfigurationLogger.java    From docker-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	@EventListener
	public void handleContextRefresh(ContextRefreshedEvent event) {
		final Environment environment = event.getApplicationContext().getEnvironment();
		LOGGER.debug("====== Environment and configuration ======");
		LOGGER.debug("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
		final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
		StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
				.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
				.forEach(prop -> {
					LOGGER.debug("{}", prop);
//					Object resolved = environment.getProperty(prop, Object.class);
//					if (resolved instanceof String) {
//						LOGGER.info("{}", environment.getProperty(prop));
//					}
				});
		LOGGER.debug("===========================================");
	}
 
Example #14
Source File: EnvironmentConfigurationLogger.java    From docker-crash-course with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	@EventListener
	public void handleContextRefresh(ContextRefreshedEvent event) {
		final Environment environment = event.getApplicationContext().getEnvironment();
		LOGGER.debug("====== Environment and configuration ======");
		LOGGER.debug("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
		final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
		StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
				.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
				.forEach(prop -> {
					LOGGER.debug("{}", prop);
//					Object resolved = environment.getProperty(prop, Object.class);
//					if (resolved instanceof String) {
//						LOGGER.info("{}", environment.getProperty(prop));
//					}
				});
		LOGGER.debug("===========================================");
	}
 
Example #15
Source File: EnvironmentDecryptApplicationInitializer.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void insert(MutablePropertySources propertySources,
		PropertySource<?> propertySource) {
	if (propertySources
			.contains(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
		if (DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME
				.equals(propertySource.getName())) {
			propertySources.addBefore(
					BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME,
					propertySource);
		}
		else {
			propertySources.addAfter(
					BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME,
					propertySource);
		}
	}
	else {
		propertySources.addFirst(propertySource);
	}
}
 
Example #16
Source File: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void explicitPropertySourcesExcludesLocalProperties() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPropertySources(propertySources);
	ppc.setProperties(new Properties() {{
		put("my.name", "local");
	}});
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
 
Example #17
Source File: BootstrapApplicationListener.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void mergeAdditionalPropertySources(MutablePropertySources environment,
		MutablePropertySources bootstrap) {
	PropertySource<?> defaultProperties = environment.get(DEFAULT_PROPERTIES);
	ExtendedDefaultPropertySource result = defaultProperties instanceof ExtendedDefaultPropertySource
			? (ExtendedDefaultPropertySource) defaultProperties
			: new ExtendedDefaultPropertySource(DEFAULT_PROPERTIES,
					defaultProperties);
	for (PropertySource<?> source : bootstrap) {
		if (!environment.contains(source.getName())) {
			result.add(source);
		}
	}
	for (String name : result.getPropertySourceNames()) {
		bootstrap.remove(name);
	}
	addOrReplace(environment, result);
	addOrReplace(bootstrap, result);
}
 
Example #18
Source File: IbisApplicationInitializer.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
	System.setProperty(EndpointImpl.CHECK_PUBLISH_ENDPOINT_PERMISSON_PROPERTY_WITH_SECURITY_MANAGER, "false");
	servletContext.log("Starting IBIS WebApplicationInitializer");

	XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
	applicationContext.setConfigLocation(XmlWebApplicationContext.CLASSPATH_URL_PREFIX + "/webApplicationContext.xml");
	applicationContext.setDisplayName("IbisApplicationInitializer");

	MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
	propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
	propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
	propertySources.addFirst(new PropertiesPropertySource("ibis", AppConstants.getInstance()));

	return applicationContext;
}
 
Example #19
Source File: PropertySourceAnnotationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void withExplicitName() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ConfigWithExplicitName.class);
	ctx.refresh();
	assertTrue("property source p1 was not added",
			ctx.getEnvironment().getPropertySources().contains("p1"));
	assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));

	// assert that the property source was added last to the set of sources
	String name;
	MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
	Iterator<org.springframework.core.env.PropertySource<?>> iterator = sources.iterator();
	do {
		name = iterator.next().getName();
	}
	while(iterator.hasNext());

	assertThat(name, is("p1"));
}
 
Example #20
Source File: PropertyMockingApplicationContextInitializer.java    From entref-spring-boot with MIT License 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    // configure a net binding instance
    Net mongoNet = this.getMongoNet();

    // register some autowire-able dependencies, to make leveraging the configured instances in a test possible
    applicationContext.getBeanFactory().registerResolvableDependency(RestTemplateBuilder.class, this.getRestTemplateBuilder());
    applicationContext.getBeanFactory().registerResolvableDependency(Net.class, mongoNet);
    applicationContext.getBeanFactory().registerResolvableDependency(MongodExecutable.class, this.getMongo(mongoNet));

    // configure the property sources that will be used by the application
    MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    MockPropertySource mockEnvVars = new MockPropertySource()
            .withProperty(Constants.ENV_DB_NAME, this.getDbName())
            .withProperty(Constants.ENV_DB_CONNSTR, "mongodb://localhost:" + mongoNet.getPort())
            .withProperty(Constants.ENV_ALLOWED_ORIGIN, this.getAllowedOrigin())
            .withProperty(Constants.ENV_EXCLUDE_FILTER, String.join(",", this.getExcludeList()));

    // inject the property sources into the application as environment variables
    propertySources.replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, mockEnvVars);
}
 
Example #21
Source File: AnnotationConditionalOnPropertyBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public BeanDefinitionRegistryPostProcessor postProcessor(ConfigurableEnvironment environment) {
    return new BeanDefinitionRegistryPostProcessor() {
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            MutablePropertySources propertySources = environment.getPropertySources();
            Map<String, Object> source = new HashMap<>();
            source.put("enabled", "true");
            propertySources.addFirst(new MapPropertySource("for @ConditionalOnProperty", source));
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }
    };
}
 
Example #22
Source File: SofaArkEmbedAppInitializer.java    From sofa-lookout with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext ctx) {
    if (!APP_NAME_SET.add(appName)) {
        throw new IllegalStateException("same appName " + appName + " can only be used once!");
    }
    ConfigurableEnvironment cenv = ctx.getEnvironment();
    MutablePropertySources mps = cenv.getPropertySources();

    MapPropertySource lookoutallSubView = getLookoutAllSubView();
    if (lookoutallSubView != null) {
        mps.addFirst(lookoutallSubView);
    }

    String prefix = appName + ".";
    MapPropertySource env = new MapPropertySource("sofaark-environment", EnvUtils.getEnvSubView(prefix));
    mps.addFirst(env);

    MapPropertySource sd = new MapPropertySource("sofaark-systemProperties", EnvUtils.getSystemPropertySubView(prefix));
    mps.addFirst(sd);
}
 
Example #23
Source File: GrayClientImportSelector.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
    String[] imports = super.selectImports(metadata);

    Environment env = getEnvironment();
    String grayEnabled = env.getProperty("gray.enabled");
    if (StringUtils.isEmpty(grayEnabled)) {
        if (ConfigurableEnvironment.class.isInstance(env)) {
            ConfigurableEnvironment environment = (ConfigurableEnvironment) env;
            MutablePropertySources m = environment.getPropertySources();
            Properties p = new Properties();
            p.put("gray.enabled", "true");
            m.addLast(new PropertiesPropertySource("defaultProperties", p));
        }
    }

    return imports;
}
 
Example #24
Source File: Application.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
    
    final Environment env = event.getApplicationContext().getEnvironment();
    log.trace("====== Environment and configuration ======");
    log.trace("Active profiles: {}", Arrays.toString(env.getActiveProfiles()));
    final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources();
    StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
            .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
            .filter(prop -> !(prop.contains("credentials") || prop.contains("password")))
            .forEach(prop -> log.trace("{}: {}", prop, env.getProperty(prop)));
    
    log.info("===========================================");
    
    log.info("Application [{} - version: {}, build time: {}] Started !", 
            buildProperties.getGroup() + ":" + buildProperties.getArtifact(), 
            buildProperties.getVersion(),
            buildProperties.getTime());
    
    log.info("===========================================");
}
 
Example #25
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 */
protected void configurePropertySources(ConfigurableEnvironment environment,
		String[] args) {
	MutablePropertySources sources = environment.getPropertySources();
	if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
		sources.addLast(
				new MapPropertySource("defaultProperties", this.defaultProperties));
	}
	if (this.addCommandLineProperties && args.length > 0) {
		String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
		if (sources.contains(name)) {
			PropertySource<?> source = sources.get(name);
			CompositePropertySource composite = new CompositePropertySource(name);
			composite.addPropertySource(new SimpleCommandLinePropertySource(
					"springApplicationCommandLineArgs", args));
			composite.addPropertySource(source);
			sources.replace(name, composite);
		}
		else {
			sources.addFirst(new SimpleCommandLinePropertySource(args));
		}
	}
}
 
Example #26
Source File: TestMetaServer.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
	super.customizePropertySources(propertySources);
	propertySources.addFirst(new PropertySource<Object>("TestAppServerProperty"){

		@Override
		public Object getProperty(String name) {
			
			if(name.equals("server.port")){
				return String.valueOf(serverPort);
			}
			return null;
		}
		
	});
}
 
Example #27
Source File: SecretBeanPostProcessor.java    From kork with Apache License 2.0 6 votes vote down vote up
SecretBeanPostProcessor(
    ConfigurableApplicationContext applicationContext, SecretManager secretManager) {
  this.applicationContext = applicationContext;
  this.secretManager = secretManager;
  MutablePropertySources propertySources =
      applicationContext.getEnvironment().getPropertySources();
  List<EnumerablePropertySource> enumerableSources = new ArrayList<>();

  for (PropertySource ps : propertySources) {
    if (ps instanceof EnumerablePropertySource) {
      enumerableSources.add((EnumerablePropertySource) ps);
    }
  }

  for (EnumerablePropertySource s : enumerableSources) {
    propertySources.replace(s.getName(), new SecretAwarePropertySource(s, secretManager));
  }
}
 
Example #28
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

	if (this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing != null) {
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
			return;
		}
	}

	if (this.propertySourceNames.isEmpty()) {
		propertySources.addLast(propertySource);
	}
	else {
		String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
		propertySources.addBefore(firstProcessed, propertySource);
	}
	this.propertySourceNames.add(name);
}
 
Example #29
Source File: ContextRefresherTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private List<String> names(MutablePropertySources propertySources) {
	List<String> list = new ArrayList<>();
	for (PropertySource<?> p : propertySources) {
		list.add(p.getName());
	}
	return list;
}
 
Example #30
Source File: PropertySourcesPlaceholderConfigurer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.propertySources == null) {
		this.propertySources = new MutablePropertySources();
		if (this.environment != null) {
			this.propertySources.addLast(
				new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
					@Override
					@Nullable
					public String getProperty(String key) {
						return this.source.getProperty(key);
					}
				}
			);
		}
		try {
			PropertySource<?> localPropertySource =
					new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
			if (this.localOverride) {
				this.propertySources.addFirst(localPropertySource);
			}
			else {
				this.propertySources.addLast(localPropertySource);
			}
		}
		catch (IOException ex) {
			throw new BeanInitializationException("Could not load properties", ex);
		}
	}

	processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
	this.appliedPropertySources = this.propertySources;
}