下面列出了org.springframework.core.env.CompositePropertySource#addPropertySource ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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));
}
}
}
/**
* Initialize Apollo Configurations Just after environment is ready.
*
* @param environment
*/
protected void initialize(ConfigurableEnvironment environment) {
if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
//already initialized
return;
}
String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
logger.debug("Apollo bootstrap namespaces: {}", namespaces);
List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);
CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
for (String namespace : namespaceList) {
Config config = ConfigService.getConfig(namespace);
composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
}
environment.getPropertySources().addFirst(composite);
}
private PropertySource<?> loadPropertySource(Resource resource, String path) {
if (resource.exists()) {
try {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(path,
resource);
if (sources != null) {
logger.info("Loaded YAML properties from: " + resource);
} else if (sources == null || sources.isEmpty()){
return null;
}
CompositePropertySource composite = new CompositePropertySource("cli-sources");
for (PropertySource propertySource : sources) {
composite.addPropertySource(propertySource);
}
return composite;
}
catch (IOException e) {
}
}
return null;
}
@Override
public PropertySource<?> locate(Environment environment) {
ServiceCombConfigPropertySource serviceCombConfigPropertySource = new ServiceCombConfigPropertySource(
ConfigConstants.PROPERTYSOURCE_NAME,
serviceCombConfigClient);
try {
serviceCombConfigPropertySource
.loadAllRemoteConfig(serviceCombConfigProperties, project);
} catch (RemoteOperationException e) {
LOGGER.error(e.getMessage(), e);
}
CompositePropertySource composite = new CompositePropertySource(ConfigConstants.PROPERTYSOURCE_NAME);
composite.addPropertySource(serviceCombConfigPropertySource);
return composite;
}
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);
}
private void processApplicationResult(CompositePropertySource composite, Environment result) {
if (result.getPropertySources() != null) { // result.getPropertySources() can be null if using xml
for (PropertySource source : result.getPropertySources()) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) source
.getSource();
composite.addPropertySource(new MapPropertySource(source
.getName(), map));
}
}
}
private void addConfigLocationFiles(ConfigurableEnvironment environment, CompositePropertySource composite) {
MutablePropertySources ps = environment.getPropertySources();
for (org.springframework.core.env.PropertySource<?> propertySource : ps) {
if (propertySource.getName().startsWith("applicationConfig: [file:")) {
logger.info("Adding {} to Cloud Config Client PropertySource", propertySource.getName());
composite.addPropertySource(propertySource);
}
}
}
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);
}
private void addPropertySource(PropertySource<?> propertySource) {
String name = propertySource.getName();
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
// We've already added a version, we need to extend it
PropertySource<?> existing = propertySources.get(name);
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);
}
}
else {
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);
}
private void initializePropertySources() {
if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) {
//already initialized
return;
}
CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME);
//sort by order asc
ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
Iterator<Integer> iterator = orders.iterator();
while (iterator.hasNext()) {
int order = iterator.next();
for (String namespace : NAMESPACE_NAMES.get(order)) {
Config config = ConfigService.getConfig(namespace);
composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
}
}
// clean up
NAMESPACE_NAMES.clear();
// add after the bootstrap property source or to the first
if (environment.getPropertySources()
.contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
// ensure ApolloBootstrapPropertySources is still the first
ensureBootstrapPropertyPrecedence(environment);
environment.getPropertySources()
.addAfter(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, composite);
} else {
environment.getPropertySources().addFirst(composite);
}
}
private void addPropertySource(ResourcePropertySource propertySource) {
String name = propertySource.getName();
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
// We've already added a version, we need to extend it
PropertySource<?> existing = propertySources.get(name);
if (existing instanceof CompositePropertySource) {
((CompositePropertySource) existing).addFirstPropertySource(propertySource.withResourceName());
}
else {
if (existing instanceof ResourcePropertySource) {
existing = ((ResourcePropertySource) existing).withResourceName();
}
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(propertySource.withResourceName());
composite.addPropertySource(existing);
propertySources.replace(name, composite);
}
}
else {
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);
}
/**
* Create a {@link CompositePropertySource} given a {@link List} of
* {@link PropertySource}s.
* @param propertySourceName the property source name.
* @param propertySources the property sources.
* @return the {@link CompositePropertySource} to use.
*/
protected CompositePropertySource doCreateCompositePropertySource(
String propertySourceName, List<PropertySource<?>> propertySources) {
CompositePropertySource compositePropertySource = new CompositePropertySource(
propertySourceName);
for (PropertySource<?> propertySource : propertySources) {
compositePropertySource.addPropertySource(propertySource);
}
return compositePropertySource;
}
@Override
protected ConfigurableEnvironment getEnvironment() {
//Bootstrap properties contain all the Config Server properties
CompositePropertySource bootstrapPropSource = new CompositePropertySource("bootstrapProperties");
String vaultPropertySourceName = "configService";
CompositePropertySource compositeProps = new CompositePropertySource(vaultPropertySourceName);
//Add vault properties that will be masked
Map<String, Object> fakeVaultProperties = new HashMap<>();
fakeVaultProperties.put(PropertyMaskingContextInitializerIntegrationTests.VAULT_TEST_SANITIZE_PROPERTY, "SecretVaultValue");
compositeProps.addPropertySource(new MapPropertySource("vault:test-data", fakeVaultProperties));
//Add credhub properties that will be masked
Map<String, Object> fakeCredhubProperties = new HashMap<>();
fakeCredhubProperties.put(PropertyMaskingContextInitializerIntegrationTests.CREDHUB_TEST_SANITIZE_PROPERTY, "SecretCredhubValue");
compositeProps.addPropertySource(new MapPropertySource("credhub-test-data", fakeCredhubProperties));
//Add Git properties that will not be masked (except the my-password which is part of the default sainitze keys)
Map<String, Object> fakeGitProperties = new HashMap<>();
fakeGitProperties.put(GIT_TEST_NON_SANITIZE_PROPERTY, "ReadableValue");
fakeGitProperties.put("my-password", "supersecret");
compositeProps.addPropertySource(new MapPropertySource("git:test-data", fakeGitProperties));
bootstrapPropSource.addPropertySource(compositeProps);
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(bootstrapPropSource);
return environment;
}
@Override
protected ConfigurableEnvironment getEnvironment() {
// Bootstrap properties contain all the Config Server properties
CompositePropertySource bootstrapPropSource = new CompositePropertySource("bootstrapProperties");
String vaultPropertySourceName = "configService";
CompositePropertySource compositeProps = new CompositePropertySource(vaultPropertySourceName);
// Add vault properties that will be masked
Map<String, Object> fakeVaultProperties = new HashMap<>();
fakeVaultProperties.put(VAULT_TEST_SANITIZE_PROPERTY, "SecretVaultValue");
compositeProps.addPropertySource(new MapPropertySource("vault:test-data", fakeVaultProperties));
// Add credhub properties that will be masked
Map<String, Object> fakeCredhubProperties = new HashMap<>();
fakeCredhubProperties.put(CREDHUB_TEST_SANITIZE_PROPERTY, "SecretCredhubValue");
compositeProps.addPropertySource(new MapPropertySource("credhub-test-data", fakeCredhubProperties));
// Add Git properties that will not be masked (except the my-password which is
// part of the default sainitze keys)
Map<String, Object> fakeGitProperties = new HashMap<>();
fakeGitProperties.put(GIT_TEST_NON_SANITIZE_PROPERTY, "ReadableValue");
fakeGitProperties.put("my-password", "supersecret");
compositeProps.addPropertySource(new MapPropertySource("git:test-data", fakeGitProperties));
bootstrapPropSource.addPropertySource(compositeProps);
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(bootstrapPropSource);
return environment;
}
@Override
public org.springframework.core.env.PropertySource<?> locate(
Environment environment) {
CompositePropertySource composite = new CompositePropertySource("configService");
for (PropertySource source : this.repository
.findOne(this.name, this.profiles, this.label, false)
.getPropertySources()) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) source.getSource();
composite.addPropertySource(new MapPropertySource(source.getName(), map));
}
return composite;
}
@Test
public void testSetEnvironment() {
ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class);
MutablePropertySources propertySources = new MutablePropertySources();
Map<String, String> propertyMap = new HashMap<>();
final String map0Key0 = "map0-Key0";
final String map1Key0 = "map1-Key0";
final String map2Key0 = "map2-Key0";
final String map3Key0 = "map3-Key0";
propertyMap.put(map0Key0, "map0-Value0");
propertyMap.put(map1Key0, "map1-Value0");
propertyMap.put(map2Key0, "map2-Value0");
propertyMap.put(map3Key0, "map3-Value0");
/*
propertySources
|- compositePropertySource0
| |- mapPropertySource0
| | |- map0-Key0 = map0-Value0
| |- compositePropertySource1
| |- mapPropertySource1
| | |- map1-Key0 = map1-Value0
| |- mapPropertySource2
| |- map2-Key0 = map2-Value0
| |- JndiPropertySource(mocked)
|- mapPropertySource3
|- map3-Key0 = map3-Value0
*/
CompositePropertySource compositePropertySource0 = new CompositePropertySource("compositePropertySource0");
propertySources.addFirst(compositePropertySource0);
HashMap<String, Object> map0 = new HashMap<>();
map0.put(map0Key0, propertyMap.get(map0Key0));
MapPropertySource mapPropertySource0 = new MapPropertySource("mapPropertySource0", map0);
compositePropertySource0.addFirstPropertySource(mapPropertySource0);
CompositePropertySource compositePropertySource1 = new CompositePropertySource("compositePropertySource1");
compositePropertySource0.addPropertySource(compositePropertySource1);
HashMap<String, Object> map1 = new HashMap<>();
map1.put(map1Key0, propertyMap.get(map1Key0));
MapPropertySource mapPropertySource1 = new MapPropertySource("mapPropertySource1", map1);
compositePropertySource1.addPropertySource(mapPropertySource1);
HashMap<String, Object> map2 = new HashMap<>();
map2.put(map2Key0, propertyMap.get(map2Key0));
MapPropertySource mapPropertySource2 = new MapPropertySource("mapPropertySource2", map2);
compositePropertySource1.addPropertySource(mapPropertySource2);
compositePropertySource1.addPropertySource(Mockito.mock(JndiPropertySource.class));
HashMap<String, Object> map3 = new HashMap<>();
map3.put(map3Key0, propertyMap.get(map3Key0));
MapPropertySource mapPropertySource3 = new MapPropertySource("mapPropertySource3", map3);
compositePropertySource0.addPropertySource(mapPropertySource3);
Mockito.when(environment.getPropertySources()).thenReturn(propertySources);
Mockito.doAnswer((Answer<String>) invocation -> {
Object[] args = invocation.getArguments();
String propertyName = (String) args[0];
if ("spring.config.name".equals(propertyName) || "spring.application.name".equals(propertyName)) {
return null;
}
String value = propertyMap.get(propertyName);
if (null == value) {
fail("get unexpected property name: " + propertyName);
}
return value;
}).when(environment).getProperty(anyString(), Matchers.eq(Object.class));
new ConfigurationSpringInitializer().setEnvironment(environment);
Map<String, Map<String, Object>> extraLocalConfig = getExtraConfigMapFromConfigUtil();
assertFalse(extraLocalConfig.isEmpty());
Map<String, Object> extraProperties = extraLocalConfig
.get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + environment.getClass().getName() + "@"
+ environment.hashCode());
assertNotNull(extraLocalConfig);
for (Entry<String, String> entry : propertyMap.entrySet()) {
assertEquals(entry.getValue(), extraProperties.get(entry.getKey()));
}
}
@Override
public PropertySource<?> locate(Environment environment) {
if (!(environment instanceof ConfigurableEnvironment)) {
return null;
}
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
String appName = properties.getName();
if (appName == null) {
appName = env.getProperty("spring.application.name");
}
List<String> profiles = Arrays.asList(env.getActiveProfiles());
String prefix = this.properties.getPrefix();
String appContext = prefix + "/" + appName;
addProfiles(this.contexts, appContext, profiles);
this.contexts.add(appContext + "/");
String defaultContext = prefix + "/" + this.properties.getDefaultContext();
addProfiles(this.contexts, defaultContext, profiles);
this.contexts.add(defaultContext + "/");
CompositePropertySource composite = new CompositePropertySource(
"aws-param-store");
for (String propertySourceContext : this.contexts) {
try {
composite.addPropertySource(create(propertySourceContext));
}
catch (Exception e) {
if (this.properties.isFailFast()) {
logger.error(
"Fail fast is set and there was an error reading configuration from AWS Parameter Store:\n"
+ e.getMessage());
ReflectionUtils.rethrowRuntimeException(e);
}
else {
logger.warn("Unable to load AWS config from " + propertySourceContext,
e);
}
}
}
return composite;
}
@Override
public PropertySource<?> locate(Environment environment) {
if (environment instanceof ConfigurableEnvironment) {
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
String appName = env.getProperty("spring.application.name");
if (appName == null) {
// use default "application" (which config client does)
appName = "application";
log.warn(
"spring.application.name is not set. Using default of 'application'");
}
List<String> profiles = Arrays.asList(env.getActiveProfiles());
String root = this.properties.getRoot();
this.contexts = new ArrayList<>();
String defaultContext = root + "/" + this.properties.getDefaultContext();
this.contexts.add(defaultContext);
addProfiles(this.contexts, defaultContext, profiles);
StringBuilder baseContext = new StringBuilder(root);
if (!appName.startsWith("/")) {
baseContext.append("/");
}
baseContext.append(appName);
this.contexts.add(baseContext.toString());
addProfiles(this.contexts, baseContext.toString(), profiles);
CompositePropertySource composite = new CompositePropertySource("zookeeper");
Collections.reverse(this.contexts);
for (String propertySourceContext : this.contexts) {
try {
PropertySource propertySource = create(propertySourceContext);
composite.addPropertySource(propertySource);
// TODO: howto call close when /refresh
}
catch (Exception e) {
if (this.properties.isFailFast()) {
ReflectionUtils.rethrowRuntimeException(e);
}
else {
log.warn("Unable to load zookeeper config from "
+ propertySourceContext, e);
}
}
}
return composite;
}
return null;
}
@Test
public void doNotDecryptBootstrapTwice() {
TextEncryptor encryptor = mock(TextEncryptor.class);
when(encryptor.decrypt("bar")).thenReturn("bar");
when(encryptor.decrypt("bar2")).thenReturn("bar2");
when(encryptor.decrypt("bar3")).thenReturn("bar3");
when(encryptor.decrypt("baz")).thenReturn("baz");
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
encryptor);
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
CompositePropertySource bootstrap = new CompositePropertySource(
BOOTSTRAP_PROPERTY_SOURCE_NAME);
bootstrap.addPropertySource(new MapPropertySource("configService",
Collections.singletonMap("foo", "{cipher}bar")));
context.getEnvironment().getPropertySources().addFirst(bootstrap);
Map<String, Object> props = new HashMap<>();
props.put("foo2", "{cipher}bar2");
props.put("bar", "{cipher}baz");
context.getEnvironment().getPropertySources().addAfter(
BOOTSTRAP_PROPERTY_SOURCE_NAME, new MapPropertySource("remote", props));
initializer.initialize(context);
// Simulate retrieval of new properties via Spring Cloud Config
props.put("foo2", "{cipher}bar3");
context.getEnvironment().getPropertySources().replace("remote",
new MapPropertySource("remote", props));
initializer.initialize(context);
verify(encryptor).decrypt("bar");
verify(encryptor).decrypt("bar2");
verify(encryptor).decrypt("bar3");
verify(encryptor, times(2)).decrypt("baz");
// Check if all encrypted properties are still decrypted
PropertySource<?> decryptedBootstrap = context.getEnvironment()
.getPropertySources().get(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME);
then(decryptedBootstrap.getProperty("foo")).isEqualTo("bar");
PropertySource<?> decrypted = context.getEnvironment().getPropertySources()
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
then(decrypted.getProperty("foo2")).isEqualTo("bar3");
then(decrypted.getProperty("bar")).isEqualTo("baz");
}
@Override
public PropertySource<?> locate(Environment environment) {
if (!(environment instanceof ConfigurableEnvironment)) {
return null;
}
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
String appName = properties.getName();
if (appName == null) {
appName = env.getProperty("spring.application.name");
}
List<String> profiles = Arrays.asList(env.getActiveProfiles());
String prefix = this.properties.getPrefix();
String appContext = prefix + "/" + appName;
addProfiles(this.contexts, appContext, profiles);
this.contexts.add(appContext);
String defaultContext = prefix + "/" + this.properties.getDefaultContext();
addProfiles(this.contexts, defaultContext, profiles);
this.contexts.add(defaultContext);
CompositePropertySource composite = new CompositePropertySource(
this.propertySourceName);
for (String propertySourceContext : this.contexts) {
try {
composite.addPropertySource(create(propertySourceContext));
}
catch (Exception e) {
if (this.properties.isFailFast()) {
logger.error(
"Fail fast is set and there was an error reading configuration from AWS Secrets Manager:\n"
+ e.getMessage());
ReflectionUtils.rethrowRuntimeException(e);
}
else {
logger.warn("Unable to load AWS secret from " + propertySourceContext,
e);
}
}
}
return composite;
}