下面列出了org.springframework.core.env.ConfigurableEnvironment#getPropertySources ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void addPropertiesFilesToEnvironmentWithSinglePropertyFromVirtualFile() {
ConfigurableEnvironment environment = new MockEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME);
assertEquals(0, propertySources.size());
String pair = "key = value";
ByteArrayResource resource = new ByteArrayResource(pair.getBytes(), "from inlined property: " + pair);
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(anyString())).willReturn(resource);
addPropertiesFilesToEnvironment(environment, resourceLoader, FOO_LOCATIONS);
assertEquals(1, propertySources.size());
assertEquals("value", environment.getProperty("key"));
}
public static JasyptEncryptorConfigurationProperties bindConfigProps(ConfigurableEnvironment environment) {
final BindHandler handler = new IgnoreErrorsBindHandler(BindHandler.DEFAULT);
final MutablePropertySources propertySources = environment.getPropertySources();
final Binder binder = new Binder(ConfigurationPropertySources.from(propertySources),
new PropertySourcesPlaceholdersResolver(propertySources),
ApplicationConversionService.getSharedInstance());
final JasyptEncryptorConfigurationProperties config = new JasyptEncryptorConfigurationProperties();
final ResolvableType type = ResolvableType.forClass(JasyptEncryptorConfigurationProperties.class);
final Annotation annotation = AnnotationUtils.findAnnotation(JasyptEncryptorConfigurationProperties.class,
ConfigurationProperties.class);
final Annotation[] annotations = new Annotation[]{annotation};
final Bindable<?> target = Bindable.of(type).withExistingValue(config).withAnnotations(annotations);
binder.bind("jasypt.encryptor", target, handler);
return config;
}
@Test
public void propertySourceOrder() throws Exception {
SimpleNamingContextBuilder.emptyActivatedContextBuilder();
ConfigurableEnvironment env = new StandardServletEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0));
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1));
assertThat(sources.precedenceOf(PropertySource.named(
StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2));
assertThat(sources.precedenceOf(PropertySource.named(
StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3));
assertThat(sources.precedenceOf(PropertySource.named(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
assertThat(sources.size(), is(5));
}
@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));
}
}
}
}
}
/**
* Traversal all {@link PropertySource} of {@link ConfigurableEnvironment}, and try to get all properties.
*/
private Map<String, Object> getAllProperties(Environment environment) {
Map<String, Object> configFromSpringBoot = new HashMap<>();
if (!(environment instanceof ConfigurableEnvironment)) {
return configFromSpringBoot;
}
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment;
if (ignoreResolveFailure()) {
configurableEnvironment.setIgnoreUnresolvableNestedPlaceholders(true);
}
for (PropertySource<?> propertySource : configurableEnvironment.getPropertySources()) {
getProperties(configurableEnvironment, propertySource, configFromSpringBoot);
}
return configFromSpringBoot;
}
@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);
}
/**
* 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));
}
}
}
private void registerPort(ConfigurableEnvironment environment) {
Integer httpPortProperty = environment.getProperty("wiremock.server.port",
Integer.class);
// If the httpPortProperty is not found it means the AutoConfigureWireMock hasn't
// been initialised.
if (httpPortProperty == null) {
return;
}
if (isHttpDynamic(httpPortProperty)) {
registerPropertySourceForDynamicEntries(environment, "wiremock.server.port",
10000, 12500, "wiremock.server.port-dynamic");
if (log.isDebugEnabled()) {
log.debug("Registered property source for dynamic http port");
}
}
int httpsPortProperty = environment.getProperty("wiremock.server.https-port",
Integer.class, 0);
if (isHttpsDynamic(httpsPortProperty)) {
registerPropertySourceForDynamicEntries(environment,
"wiremock.server.https-port", 12500, 15000,
"wiremock.server.https-port-dynamic");
if (log.isDebugEnabled()) {
log.debug("Registered property source for dynamic https port");
}
}
else if (httpsPortProperty == -1) {
MutablePropertySources propertySources = environment.getPropertySources();
addPropertySource(propertySources);
Map<String, Object> source = ((MapPropertySource) propertySources
.get("wiremock")).getSource();
source.put("wiremock.server.https-port-dynamic", true);
if (log.isDebugEnabled()) {
log.debug(
"Registered property source for dynamic https with https port property set to -1");
}
}
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment envi = event.getEnvironment();
MutablePropertySources mps = envi.getPropertySources();
for (PropertySource<?> ps : mps) {
System.out.println("SpringBoot对应Enviroment已经准备完毕,但此时上下文Context还没有创建,得到PropertySource-->" + ps);
}
}
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);
}
}
}
@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
final ConfigurableEnvironment springEnv = applicationContext.getEnvironment();
final MutablePropertySources propSources = springEnv.getPropertySources();
for (String location : getPropertyLocations(applicationContext)) {
tryAddPropertySource(applicationContext, propSources, location);
}
addPropertySources(applicationContext, propSources);
}
/**
* Gets the mutable property sources object from the environment.
*
* @return the mutable property sources.
* @throws Exception if the mutable property sources couldn't be obtained.
*/
protected MutablePropertySources getMutablePropertySources() throws Exception
{
// Ensure we have a configurable environment so we can remove the property source.
if (!(environment instanceof ConfigurableEnvironment))
{
throw new Exception("The environment is not an instance of ConfigurableEnvironment and needs to be for this test to work.");
}
// Return the property sources from the configurable environment.
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment;
return configurableEnvironment.getPropertySources();
}
@BeforeEach
void setup() {
// create Spring Application dynamically
application = new SpringApplication(ValidationApplication.class);
// setting test properties for our Spring Application
properties = new Properties();
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addFirst(new PropertiesPropertySource("application-test", properties));
application.setEnvironment(environment);
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
String[] defaultKeys = { "password", "secret", "key", "token", ".*credentials.*", "vcap_services" };
Set<String> propertiesToSanitize = Stream.of(defaultKeys).collect(Collectors.toSet());
PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();
if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
}
for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
configServiceNestedPropertySources
.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
}
}
Stream<String> vaultKeyNameStream = configServiceNestedPropertySources.stream()
.filter(ps -> ps instanceof EnumerablePropertySource)
.filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN)
|| ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::<String>stream);
propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));
PropertiesPropertySource envKeysToSanitize = new PropertiesPropertySource(SANITIZE_ENV_KEY,
mergeClientProperties(propertySources, propertiesToSanitize));
environment.getPropertySources().addFirst(envKeysToSanitize);
applicationContext.setEnvironment(environment);
}
@Test
public void testParentExecutionId() {
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> myMap = new HashMap<>();
myMap.put("spring.cloud.task.parentExecutionId", 789);
propertySources
.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
this.context.setEnvironment(environment);
this.context.refresh();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
verifyTaskExecution(0, false, null, null, null, 789L);
}
private void disableEndpoint(final ConfigurableListableBeanFactory beanFactory) {
final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
final MutablePropertySources propertySources = env.getPropertySources();
propertySources.addFirst(
new MapPropertySource(endpoint + "PropertySource", singletonMap("endpoints." + endpoint + ".enabled", false))
);
}
private static Map<String, PropertySource<?>> doGetPropertySources(ConfigurableEnvironment environment) {
Map<String, PropertySource<?>> map = new LinkedHashMap<String, PropertySource<?>>();
MutablePropertySources sources = environment.getPropertySources();
for (PropertySource<?> source : sources) {
extract("", map, source);
}
return map;
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
increaseInvocationCount();
if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) {
CfJdbcEnv cfJdbcEnv = new CfJdbcEnv();
CfJdbcService cfJdbcService = null;
try {
cfJdbcService = cfJdbcEnv.findJdbcService();
cfJdbcService = this.isEnabled(cfJdbcService, environment) ? cfJdbcService : null;
} catch (Exception e) {
List<CfJdbcService> jdbcServices = cfJdbcEnv.findJdbcServices().stream()
.filter(service -> this.isEnabled(service, environment))
.collect(Collectors.toList());
if (jdbcServices.size() > 1) {
if (invocationCount == 1) {
DEFERRED_LOG.debug(
"Skipping execution of CfDataSourceEnvironmentPostProcessor. "
+ e.getMessage());
}
return;
}
cfJdbcService = jdbcServices.size() == 1 ? jdbcServices.get(0) : null;
}
if (cfJdbcService != null) {
ConnectorLibraryDetector.assertNoConnectorLibrary();
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("spring.datasource.url", cfJdbcService.getJdbcUrl());
properties.put("spring.datasource.username", cfJdbcService.getUsername());
properties.put("spring.datasource.password", cfJdbcService.getPassword());
Object driverClassName = cfJdbcService.getDriverClassName();
if (driverClassName != null) {
properties.put("spring.datasource.driver-class-name", driverClassName);
}
MutablePropertySources propertySources = environment.getPropertySources();
if (propertySources.contains(
CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
propertySources.addAfter(
CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
new MapPropertySource("cfenvjdbc", properties));
}
else {
propertySources
.addFirst(new MapPropertySource("cfenvjdbc", properties));
}
if (invocationCount == 1) {
DEFERRED_LOG.info(
"Setting spring.datasource properties from bound service ["
+ cfJdbcService.getName() + "]");
}
}
}
else {
DEFERRED_LOG.debug(
"Not setting spring.datasource.url, not in Cloud Foundry Environment");
}
}
public static void addListenerIfAutoRefreshed(
final NacosPropertySource nacosPropertySource, final Properties properties,
final ConfigurableEnvironment environment) {
if (!nacosPropertySource.isAutoRefreshed()) { // Disable Auto-Refreshed
return;
}
final String dataId = nacosPropertySource.getDataId();
final String groupId = nacosPropertySource.getGroupId();
final String type = nacosPropertySource.getType();
final NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(
beanFactory);
try {
ConfigService configService = nacosServiceFactory
.createConfigService(properties);
Listener listener = new AbstractListener() {
@Override
public void receiveConfigInfo(String config) {
String name = nacosPropertySource.getName();
NacosPropertySource newNacosPropertySource = new NacosPropertySource(
dataId, groupId, name, config, type);
newNacosPropertySource.copy(nacosPropertySource);
MutablePropertySources propertySources = environment
.getPropertySources();
// replace NacosPropertySource
propertySources.replace(name, newNacosPropertySource);
}
};
if (configService instanceof EventPublishingConfigService) {
((EventPublishingConfigService) configService).addListener(dataId,
groupId, type, listener);
}
else {
configService.addListener(dataId, groupId, listener);
}
}
catch (NacosException e) {
throw new RuntimeException(
"ConfigService can't add Listener with properties : " + properties,
e);
}
}
List<ConnectionEndpoint> getConfiguredConnectionEndpoints(Environment environment) {
List<ConnectionEndpoint> connectionEndpoints = new ArrayList<>();
if (environment instanceof ConfigurableEnvironment) {
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment;
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
if (propertySources != null) {
Pattern pattern = Pattern.compile(MATCHING_PROPERTY_PATTERN);
for (PropertySource<?> propertySource : propertySources) {
if (propertySource instanceof EnumerablePropertySource) {
EnumerablePropertySource<?> enumerablePropertySource =
(EnumerablePropertySource<?>) propertySource;
String[] propertyNames = enumerablePropertySource.getPropertyNames();
Arrays.stream(ArrayUtils.nullSafeArray(propertyNames, String.class))
.filter(propertyName-> pattern.matcher(propertyName).find())
.forEach(propertyName -> {
String propertyValue = environment.getProperty(propertyName);
if (StringUtils.hasText(propertyValue)) {
int defaultPort = propertyName.contains("servers")
? DEFAULT_CACHE_SERVER_PORT
: DEFAULT_LOCATOR_PORT;
String[] propertyValueArray = trim(propertyValue.split(","));
ConnectionEndpointList list =
ConnectionEndpointList.parse(defaultPort, propertyValueArray);
connectionEndpoints.addAll(list);
}
});
}
}
}
}
return connectionEndpoints;
}