org.springframework.core.env.PropertySource Java Examples

The following examples show how to use org.springframework.core.env.PropertySource. 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: LeasingVaultPropertySourceLocator.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
private PropertySource<?> createVaultPropertySource(RequestedSecret secret,
		SecretBackendMetadata accessor) {

	if (accessor instanceof LeasingSecretBackendMetadata) {
		((LeasingSecretBackendMetadata) accessor).beforeRegistration(secret,
				this.secretLeaseContainer);
	}

	LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource(
			accessor.getName(), this.secretLeaseContainer, secret,
			accessor.getPropertyTransformer());

	if (accessor instanceof LeasingSecretBackendMetadata) {
		((LeasingSecretBackendMetadata) accessor).afterRegistration(secret,
				this.secretLeaseContainer);
	}

	return propertySource;
}
 
Example #2
Source File: VaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocatePropertySourcesInEachPathSpecifiedWhenApplicationNameContainsSeveral() {

	VaultKeyValueBackendProperties backendProperties = new VaultKeyValueBackendProperties();
	backendProperties.setApplicationName("wintermute,straylight,icebreaker/armitage");
	backendProperties.setProfiles(Arrays.asList("vermillion", "periwinkle"));

	this.propertySourceLocator = new VaultPropertySourceLocator(this.operations,
			new VaultProperties(),
			VaultPropertySourceLocatorSupport.createConfiguration(backendProperties));

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).extracting("name").contains(
			"secret/wintermute", "secret/straylight", "secret/icebreaker/armitage",
			"secret/wintermute/vermillion", "secret/wintermute/periwinkle",
			"secret/straylight/vermillion", "secret/straylight/periwinkle",
			"secret/icebreaker/armitage/vermillion",
			"secret/icebreaker/armitage/periwinkle");
}
 
Example #3
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example #4
Source File: CCPropertySourceLoader.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {

		logger.info("load PropertySource -> name:{},profile:{}", name, profile);
		if (profile == null) {
			Properties properties = loadProperties(name,resource);
			if (profiles == null) {
				profiles = properties.getProperty("spring.profiles.active");
			} else {
				logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
			}
			// 如果指定了profile,则也不加载远程配置
			if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
				ccContext.init(properties, true);
				ccContext.mergeRemoteProperties(properties);
			}

			if (!properties.isEmpty()) {
				return new PropertiesPropertySource(name, properties);
			}
		}
		return null;
	}
 
Example #5
Source File: VaultPropertySourceLocatorSupport.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Create {@link PropertySource}s given {@link Environment} from the property
 * configuration.
 * @param environment must not be {@literal null}.
 * @return a {@link List} of ordered {@link PropertySource}s.
 */
protected List<PropertySource<?>> doCreatePropertySources(Environment environment) {

	Collection<SecretBackendMetadata> secretBackends = this.propertySourceLocatorConfiguration
			.getSecretBackends();
	List<SecretBackendMetadata> sorted = new ArrayList<>(secretBackends);
	List<PropertySource<?>> propertySources = new ArrayList<>();

	AnnotationAwareOrderComparator.sort(sorted);

	propertySources.addAll(doCreateKeyValuePropertySources(environment));

	for (SecretBackendMetadata backendAccessor : sorted) {

		PropertySource<?> vaultPropertySource = createVaultPropertySource(
				backendAccessor);
		propertySources.add(vaultPropertySource);
	}

	return propertySources;
}
 
Example #6
Source File: ContextRefresherOrderingIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void orderingIsCorrect() {
	refresher.refresh();
	MutablePropertySources propertySources = environment.getPropertySources();
	PropertySource<?> test1 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering1");
	PropertySource<?> test2 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering2");
	PropertySource<?> test3 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering3");
	int index1 = propertySources.precedenceOf(test1);
	int index2 = propertySources.precedenceOf(test2);
	int index3 = propertySources.precedenceOf(test3);
	assertThat(index1).as("source1 index not less then source2").isLessThan(index2);
	assertThat(index2).as("source2 index not less then source3").isLessThan(index3);
}
 
Example #7
Source File: LeasingVaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocateLeaseAwareSources() {

	RequestedSecret rotating = RequestedSecret.rotating("secret/rotating");
	DefaultSecretBackendConfigurer configurer = new DefaultSecretBackendConfigurer();
	configurer.add(rotating);
	configurer.add("database/mysql/creds/readonly");

	this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
			new VaultProperties(), configurer, this.secretLeaseContainer);

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	verify(this.secretLeaseContainer).addRequestedSecret(rotating);
	verify(this.secretLeaseContainer).addRequestedSecret(
			RequestedSecret.renewable("database/mysql/creds/readonly"));
}
 
Example #8
Source File: GspAutoConfiguration.java    From grails-boot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void updateFlatConfig() {
    super.updateFlatConfig();
    if(this.environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment configurableEnv = ((ConfigurableEnvironment)environment);
        for(PropertySource<?> propertySource : configurableEnv.getPropertySources()) {
            if(propertySource instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource)propertySource;
                for(String propertyName : enumerablePropertySource.getPropertyNames()) {
                    flatConfig.put(propertyName, enumerablePropertySource.getProperty(propertyName));
                }
            }
        }
    }
}
 
Example #9
Source File: VcapPropertySourceUnitTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void fromEnvironmentIsSuccessful() {

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	MutablePropertySources propertySources = spy(new MutablePropertySources());

	PropertySource mockVcapPropertySource = mock(EnumerablePropertySource.class);

	when(mockEnvironment.getPropertySources()).thenReturn(propertySources);
	doReturn(mockVcapPropertySource).when(propertySources).get(eq("vcap"));
	when(mockVcapPropertySource.containsProperty(anyString())).thenReturn(true);
	when(mockVcapPropertySource.getName()).thenReturn("vcap");

	VcapPropertySource propertySource = VcapPropertySource.from(mockEnvironment);

	assertThat(propertySource).isNotNull();
	assertThat(propertySource.getSource()).isEqualTo(mockVcapPropertySource);

	verify(mockEnvironment, times(1)).getPropertySources();
	verify(propertySources, times(1)).get(eq("vcap"));
	verify(mockVcapPropertySource, times(1))
		.containsProperty(eq("vcap.application.name"));
	verify(mockVcapPropertySource, times(1))
		.containsProperty(eq("vcap.application.uris"));
}
 
Example #10
Source File: ServiceInfoPropertySourceAdapter.java    From spring-cloud-services-connector with Apache License 2.0 6 votes vote down vote up
private void conditionallyExcludeRabbitAutoConfiguration() {
	if (appIsBoundToRabbitMQ()) {
		return;
	}

	Map<String, Object> properties = new LinkedHashMap<>();
	String existingExcludes = environment.getProperty(SPRING_AUTOCONFIGURE_EXCLUDE);
	if (existingExcludes == null) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS);
	} else if (!existingExcludes.contains(RABBIT_AUTOCONFIG_CLASS)) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS + "," + existingExcludes);
	}

	PropertySource<?> propertySource = new MapPropertySource("springCloudServicesRabbitAutoconfigExcluder",
			properties);
	environment.getPropertySources().addFirst(propertySource);
}
 
Example #11
Source File: EncryptablePropertySourceBeanFactoryPostProcessor.java    From jasypt-spring-boot with MIT License 6 votes vote down vote up
private PropertySource createPropertySource(AnnotationAttributes attributes, ConfigurableEnvironment environment, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, List<PropertySourceLoader> loaders) throws Exception {
    String name = generateName(attributes.getString("name"));
    String[] locations = attributes.getStringArray("value");
    boolean ignoreResourceNotFound = attributes.getBoolean("ignoreResourceNotFound");
    CompositePropertySource compositePropertySource = new CompositePropertySource(name);
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    for (String location : locations) {
        String resolvedLocation = environment.resolveRequiredPlaceholders(location);
        Resource resource = resourceLoader.getResource(resolvedLocation);
        if (!resource.exists()) {
            if (!ignoreResourceNotFound) {
                throw new IllegalStateException(String.format("Encryptable Property Source '%s' from location: %s Not Found", name, resolvedLocation));
            } else {
                log.info("Ignoring NOT FOUND Encryptable Property Source '{}' from locations: {}", name, resolvedLocation);
            }
        } else {
            String actualName = name + "#" + resolvedLocation;
            loadPropertySource(loaders, resource, actualName)
                    .ifPresent(psources -> psources.forEach(compositePropertySource::addPropertySource));
        }
    }
    return new EncryptableEnumerablePropertySourceWrapper<>(compositePropertySource, resolver, propertyFilter);
}
 
Example #12
Source File: FlowableRestApplicationTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void contextShouldLoadPropertiesInACorrectOrder() {
    assertThat(environment.getPropertySources())
        .extracting(PropertySource::getName)
        .containsExactly(
            "configurationProperties",
            "Inlined Test Properties",
            "systemProperties",
            "systemEnvironment",
            "random",
            "class path resource [db.properties]",
            "class path resource [engine.properties]",
            "applicationConfig: [classpath:/application.properties]",
            "flowableDefaultConfig: [classpath:/flowable-default.properties]",
            "flowable-liquibase-override",
            "Management Server"
        );
}
 
Example #13
Source File: AppContextEventListener.java    From kafka-graphs with Apache License 2.0 6 votes vote down vote up
private void logActiveProperties(ConfigurableEnvironment env) {
    List<MapPropertySource> propertySources = new ArrayList<>();

    for (PropertySource<?> source : env.getPropertySources()) {
        if (source instanceof MapPropertySource && source.getName().contains("applicationConfig")) {
            propertySources.add((MapPropertySource) source);
        }
    }

    propertySources.stream()
        .map(propertySource -> propertySource.getSource().keySet())
        .flatMap(Collection::stream)
        .distinct()
        .sorted()
        .forEach(key -> {
            try {
                log.debug(key + "=" + env.getProperty(key));
            } catch (Exception e) {
                log.warn("{} -> {}", key, e.getMessage());
            }
        });
}
 
Example #14
Source File: EnvProp.java    From radar with Apache License 2.0 6 votes vote down vote up
public Map<String, Map<String, Object>> getAllEnv() {
	Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();		
	for (Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) {
		PropertySource<?> source = entry.getValue();
		String sourceName = entry.getKey();
		if (source instanceof EnumerablePropertySource) {
			EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
			Map<String, Object> properties = new LinkedHashMap<String, Object>();
			for (String name : enumerable.getPropertyNames()) {
				properties.put(name, sanitize(name, enumerable.getProperty(name)));
			}
			result.put(sourceName, properties);				
		}
	}
	return result;
}
 
Example #15
Source File: SpringConfigurationPropertySources.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
private ConfigurationPropertySource fetchNext() {
    if (this.next == null) {
        if (this.iterators.isEmpty()) {
            return null;
        }
        if (!this.iterators.peek().hasNext()) {
            this.iterators.pop();
            return fetchNext();
        }
        PropertySource<?> candidate = this.iterators.peek().next();
        if (candidate.getSource() instanceof ConfigurableEnvironment) {
            push((ConfigurableEnvironment) candidate.getSource());
            return fetchNext();
        }
        if (isIgnored(candidate)) {
            return fetchNext();
        }
        this.next = this.adapter.apply(candidate);
    }
    return this.next;
}
 
Example #16
Source File: CustomConfiguredSessionCachingIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
private Function<ConfigurableApplicationContext, ConfigurableApplicationContext> newSpringSessionGemFirePropertiesConfigurationFunction() {

		return applicationContext -> {

			PropertySource springSessionGemFireProperties = new MockPropertySource("TestSpringSessionGemFireProperties")
				.withProperty(springSessionPropertyName("cache.client.region.shortcut"), "LOCAL")
				.withProperty(springSessionPropertyName("session.attributes.indexable"), "one, two")
				.withProperty(springSessionPropertyName("session.expiration.max-inactive-interval-seconds"), "600")
				.withProperty(springSessionPropertyName("cache.client.pool.name"), "MockPool")
				.withProperty(springSessionPropertyName("session.region.name"), "MockRegion")
				.withProperty(springSessionPropertyName("cache.server.region.shortcut"), "REPLICATE")
				.withProperty(springSessionPropertyName("session.serializer.bean-name"), "MockSessionSerializer");

			applicationContext.getEnvironment().getPropertySources().addFirst(springSessionGemFireProperties);

			return applicationContext;
		};
	}
 
Example #17
Source File: MqEnvProp.java    From pmq with Apache License 2.0 6 votes vote down vote up
public Map<String, Map<String, Object>> getAllEnv() {  
	Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();		
	for (Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) {
		PropertySource<?> source = entry.getValue();
		String sourceName = entry.getKey();
		if (source instanceof EnumerablePropertySource) {
			EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
			Map<String, Object> properties = new LinkedHashMap<String, Object>();
			for (String name : enumerable.getPropertyNames()) {
				properties.put(name, sanitize(name, enumerable.getProperty(name)));
			}
			result.put(sourceName, properties);				
		}
	}
	return result;
}
 
Example #18
Source File: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example #19
Source File: ResourceLoadFactory.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    PropertySource<?> propSource = null;
    String propName = name;
    if (StringUtils.isEmpty(propName)) {
        propName = getNameForResource(resource.getResource());
    }
    if (resource.getResource().exists()) {
        String fileName = resource.getResource().getFilename();
        for (PropertySourceLoader loader : loaders) {
            if (checkFileType(fileName, loader.getFileExtensions())) {
                List<PropertySource<?>> propertySources = loader.load(propName, resource.getResource());
                if (!propertySources.isEmpty()) {
                    propSource = propertySources.get(0);
                }
            }
        }
    } else {
        throw new FileNotFoundException(propName + "对应文件'" + resource.getResource().getFilename() + "'不存在");
    }
    return propSource;
}
 
Example #20
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 #21
Source File: PriceCalculationEnvironmentPostProcessor.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

    PropertySource<?> system = environment.getPropertySources()
        .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

    Map<String, Object> prefixed = new LinkedHashMap<>();

    if (!hasOurPriceProperties(system)) {
        // Baeldung-internal code so this doesn't break other examples
        logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
            GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
        prefixed = names.stream()
            .collect(Collectors.toMap(this::rename, this::getDefaultValue));
        environment.getPropertySources()
            .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
        return;
    }

    prefixed = names.stream()
        .collect(Collectors.toMap(this::rename, system::getProperty));
    environment.getPropertySources()
        .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));

}
 
Example #22
Source File: PropertySourceLocator.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
static Collection<PropertySource<?>> locateCollection(PropertySourceLocator locator,
		Environment environment) {
	PropertySource<?> propertySource = locator.locate(environment);
	if (propertySource == null) {
		return Collections.emptyList();
	}
	if (CompositePropertySource.class.isInstance(propertySource)) {
		Collection<PropertySource<?>> sources = ((CompositePropertySource) propertySource)
				.getPropertySources();
		List<PropertySource<?>> filteredSources = new ArrayList<>();
		for (PropertySource<?> p : sources) {
			if (p != null) {
				filteredSources.add(p);
			}
		}
		return filteredSources;
	}
	else {
		return Arrays.asList(propertySource);
	}
}
 
Example #23
Source File: JsonPropertyContextInitializer.java    From tutorials with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    try {
        Resource resource = configurableApplicationContext.getResource("classpath:configprops.json");
        Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
        Set<Map.Entry> set = readValue.entrySet();
        List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
        for (PropertySource propertySource : propertySources) {
            configurableApplicationContext.getEnvironment()
                .getPropertySources()
                .addFirst(propertySource);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: DSSSpringApplication.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrNot) {
    StandardEnvironment environment = (StandardEnvironment) env;
    PropertySource propertySource = environment.getPropertySources().get("bootstrapProperties");
    if(propertySource == null) {
        return;
    }
    CompositePropertySource source = (CompositePropertySource) propertySource;
    for (String key: source.getPropertyNames()) {
        Object val = source.getProperty(key);
        if(val == null) {
            continue;
        }
        if(isUpdateOrNot) {
            logger.info("update remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.set(key, val.toString());
        } else {
            logger.info("add remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.setIfNotExists(key, val.toString());
        }
    }
}
 
Example #25
Source File: LauncherInfoContributor.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Override
protected PropertySource<?> toSimplePropertySource() {
    Properties props = new Properties();

    AtomicInteger index = new AtomicInteger(0);
    getProperties().getArchives().forEach(archive -> {
        props.setProperty("archives[" + index.get() + "]", archive);
        index.getAndIncrement();
    });

    copyIfSet(props, "git.branch");
    String commitId = getProperties().getGit().getShortCommitId();
    if (commitId != null) {
        props.put("git.commit.id", commitId);
    }
    copyIfSet(props, "git.commit.time");
    return new PropertiesPropertySource("launcher", props);
}
 
Example #26
Source File: ConfigurationPropertySources.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
/**
 * Attach a {@link ConfigurationPropertySource} support to the specified
 * {@link Environment}. Adapts each {@link PropertySource} managed by the environment
 * to a {@link ConfigurationPropertySource} and allows classic
 * {@link PropertySourcesPropertyResolver} calls to resolve using
 * {@link ConfigurationPropertyName configuration property names}.
 * <p>
 * The attached resolver will dynamically track any additions or removals from the
 * underlying {@link Environment} property sources.
 *
 * @param environment the source environment (must be an instance of
 *                    {@link ConfigurableEnvironment})
 * @see #get(Environment)
 */
public static void attach(Environment environment) {
    Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
    MutablePropertySources sources = ((ConfigurableEnvironment) environment)
            .getPropertySources();
    PropertySource<?> attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME);
    if (attached != null && attached.getSource() != sources) {
        sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
        attached = null;
    }
    if (attached == null) {
        sources.addFirst(new ConfigurationPropertySourcesPropertySource(
                ATTACHED_PROPERTY_SOURCE_NAME,
                new SpringConfigurationPropertySources(sources)));
    }
}
 
Example #27
Source File: MyEnvironmentPostProcessor.java    From springCloud with MIT License 5 votes vote down vote up
private PropertySource<?> loadProfiles(Resource resource) {
    if (!resource.exists()) {
        throw new IllegalArgumentException("资源" + resource + "不存在");
    }
    try {
        //从输入流中加载一个Properties对象
        properties.load(resource.getInputStream());
        return new PropertiesPropertySource(resource.getFilename(), properties);
    }catch (IOException ex) {
        throw new IllegalStateException("加载配置文件失败" + resource, ex);
    }
}
 
Example #28
Source File: ConfigServerServiceConnector.java    From spring-cloud-services-connector with Apache License 2.0 5 votes vote down vote up
@Override
protected PropertySource<?> toPropertySource(ConfigServerServiceInfo serviceInfo) {
	Map<String, Object> properties = new LinkedHashMap<>();
	properties.put(SPRING_CLOUD_CONFIG_URI, serviceInfo.getUri());
	properties.put(SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID, serviceInfo.getClientId());
	properties.put(SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET, serviceInfo.getClientSecret());
	properties.put(SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI, serviceInfo.getAccessTokenUri());
	return new MapPropertySource(PROPERTY_SOURCE_NAME, properties);
}
 
Example #29
Source File: ExtendPropertySourcesRunListener.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
    // 从 ConfigurableApplicationContext 获取 ConfigurableEnvironment
    ConfigurableEnvironment environment = context.getEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    // 通过名称获取名为 "systemProperties" 的 PropertySource(实现使用常量)
    PropertySource propertySource = propertySources.get(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
    // 将 "systemProperties" 的 PropertySource 添加在 "contextPrepared" 之前(由 contextPrepared 方法添加),提高优先级
    propertySources.addBefore("contextPrepared", propertySource);
}
 
Example #30
Source File: MyEnvironmentPostProcessor.java    From springCloud with MIT License 5 votes vote down vote up
private PropertySource<?> loadProfiles(Resource resource) {
    if (!resource.exists()) {
        throw new IllegalArgumentException("资源" + resource + "不存在");
    }
    try {
        //从输入流中加载一个Properties对象
        properties.load(resource.getInputStream());
        return new PropertiesPropertySource(resource.getFilename(), properties);
    }catch (IOException ex) {
        throw new IllegalStateException("加载配置文件失败" + resource, ex);
    }
}