public void addKeyVaultPropertySource() { final String clientId = getProperty(environment, Constants.AZURE_CLIENTID); final String clientKey = getProperty(environment, Constants.AZURE_CLIENTKEY); final String vaultUri = getProperty(environment, Constants.AZURE_KEYVAULT_VAULT_URI); final long timeAcquiringTimeoutInSeconds = environment.getProperty( Constants.AZURE_TOKEN_ACQUIRE_TIMEOUT_IN_SECONDS, Long.class, 60L); final KeyVaultClient kvClient = new KeyVaultClient( new AzureKeyVaultCredential(clientId, clientKey, timeAcquiringTimeoutInSeconds)); try { final MutablePropertySources sources = environment.getPropertySources(); final KeyVaultOperation kvOperation = new KeyVaultOperation(kvClient, vaultUri); if (sources.contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new KeyVaultPropertySource(kvOperation)); } else { sources.addFirst(new KeyVaultPropertySource(kvOperation)); } } catch (Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } }
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { // 此处可以http方式 到配置服务器拉取一堆公共配置+本项目个性配置的json串,拼到Properties里 // ......省略new Properties的过程 MutablePropertySources propertySources = environment.getPropertySources(); // addLast 结合下面的 getOrder() 保证顺序 读者也可以试试其他姿势的加载顺序 try { Properties props = getConfig(environment); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); if ("druid.writer.password,druid.reader.password".contains(keyStr)) { String dkey = props.getProperty("druid.key"); dkey = DataUtil.isEmpty(dkey) ? Constants.DB_KEY : dkey; value = SecurityUtil.decryptDes(value, dkey.getBytes()); props.setProperty(keyStr, value); } PropertiesUtil.getProperties().put(keyStr, value); } propertySources.addLast(new PropertiesPropertySource("thirdEnv", props)); } catch (IOException e) { logger.error("", e); } }
private void addDefaultProperty(ConfigurableEnvironment environment, String name, String value) { MutablePropertySources sources = environment.getPropertySources(); Map<String, Object> map = null; if (sources.contains("defaultProperties")) { PropertySource<?> source = sources.get("defaultProperties"); if (source instanceof MapPropertySource) { map = ((MapPropertySource) source).getSource(); } } else { map = new LinkedHashMap<>(); sources.addLast(new MapPropertySource("defaultProperties", map)); } if (map != null) { map.put(name, value); } }
@Override public Stream<String> getPropertyNames() throws UnsupportedOperationException { List<String> names = new LinkedList<>(); if (ConfigurableEnvironment.class.isAssignableFrom(getEnvironment().getClass())) { MutablePropertySources propertySources = ((ConfigurableEnvironment) getEnvironment()).getPropertySources(); if (propertySources != null) { Iterator<PropertySource<?>> i = propertySources.iterator(); while (i.hasNext()) { PropertySource<?> source = i.next(); if (source instanceof EnumerablePropertySource) { String[] propertyNames = ((EnumerablePropertySource<?>) source).getPropertyNames(); if (propertyNames != null) { names.addAll(Arrays.asList(propertyNames)); } } } } } return names.stream(); }
@Override public void initialize(ConfigurableApplicationContext applicationContext) { final ConfigurableEnvironment configurableEnvironment = applicationContext.getEnvironment(); configurableEnvironment.setDefaultProfiles(Constants.STANDARD_DATABASE); final MutablePropertySources propertySources = configurableEnvironment.getPropertySources(); AwsCloudRuntimeConfig.createPropertySource().ifPresent(awsPropertySource -> { propertySources.addLast(awsPropertySource); LOG.info("Using Amazon RDS profile"); configurableEnvironment.setActiveProfiles(Constants.AMAZON_DATABASE); }); LiquibaseConfig.replaceLiquibaseServiceLocator(); }
@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")); }
@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(port); } return null; } }); }
@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; } }); }
@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}")); }
public void postProcess(ConfigurableListableBeanFactory beanFactory) { // 注册 Spring 属性配置 PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); MutablePropertySources mutablePropertySources = new MutablePropertySources(); mutablePropertySources.addLast(new PropertySource<String>(Configs.class.getName()) { @Override public String getProperty(String name) { return Configs.getString(name); } }); configurer.setPropertySources(mutablePropertySources); configurer.postProcessBeanFactory(beanFactory); /* * 注册 @ConfigValue 处理器. ConfigValueBeanPostProcessor 实现了 ApplicationListener 接口, 不能使用 * beanFactory.addBeanPostProcessor() 来注册实例. */ beanFactory.registerSingleton(ConfigValueBeanPostProcessor.class.getName(), new ConfigValueBeanPostProcessor(beanFactory)); }
private PropertySources loadPropertySources(String[] locations, boolean mergeDefaultSources) { try { PropertySourcesLoader loader = new PropertySourcesLoader(); for (String location : locations) { Resource resource = this.resourceLoader .getResource(this.environment.resolvePlaceholders(location)); String[] profiles = this.environment.getActiveProfiles(); for (int i = profiles.length; i-- > 0;) { String profile = profiles[i]; loader.load(resource, profile); } loader.load(resource); } MutablePropertySources loaded = loader.getPropertySources(); if (mergeDefaultSources) { for (PropertySource<?> propertySource : this.propertySources) { loaded.addLast(propertySource); } } return loaded; } catch (IOException ex) { throw new IllegalStateException(ex); } }
public static void finishAndRelocate(MutablePropertySources propertySources) { String name = APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME; ConfigurationPropertySources removed = (ConfigurationPropertySources) propertySources .get(name); if (removed != null) { for (PropertySource<?> propertySource : removed.sources) { if (propertySource instanceof EnumerableCompositePropertySource) { EnumerableCompositePropertySource composite = (EnumerableCompositePropertySource) propertySource; for (PropertySource<?> nested : composite.getSource()) { propertySources.addAfter(name, nested); name = nested.getName(); } } else { propertySources.addAfter(name, propertySource); } } propertySources.remove(APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME); } }
/** * 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( name + "-" + args.hashCode(), args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { Properties properties = new Properties(); addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application."); addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services."); MutablePropertySources propertySources = environment.getPropertySources(); if (propertySources.contains( CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { propertySources.addAfter( CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, new PropertiesPropertySource("vcap", properties)); } else { propertySources .addFirst(new PropertiesPropertySource("vcap", properties)); } } }
@Deprecated private Foo bindFoo(final String values) throws Exception { Properties properties = PropertiesLoaderUtils .loadProperties(new ByteArrayResource(values.getBytes())); if (this.usePropertySource) { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); } else { this.factory.setProperties(properties); } this.factory.afterPropertiesSet(); return this.factory.getObject(); }
@Test public void testAzureKvPropertySourceNotInitialized() { final MutablePropertySources sources = ((ConfigurableEnvironment) context.getEnvironment()).getPropertySources(); assertFalse("PropertySources should not contains azurekv when enabled=false", sources.contains(Constants.AZURE_KEYVAULT_PROPERTYSOURCE_NAME)); }
@Test public void customizePropertySources() { MutablePropertySources propertySources = new MutablePropertySources(); ReversePropertySourcesStandardServletEnvironment env = new ReversePropertySourcesStandardServletEnvironment(); env.customizePropertySources(propertySources); String[] sourceNames = { StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME }; List<String> result = new ArrayList<>(); propertySources.forEach(a -> result.add(a.getName())); Assert.assertArrayEquals(sourceNames, result.toArray()); }
/** * {@inheritDoc} * <p>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 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; }
/** * Returns the property key/value pairs found in {@code sources} and returns them in a {@code Map}. Only instances * of {@code EnumerablePropertySource} are considered. If {@code sources} contains other types of * {@code PropertySource}, they will be ignored, and <em>not</em> included in the returned {@code Map}. * <p> * If {@code prefix} is provided, only properties that start with the supplied prefix will be included in the * returned {@code Map}. If {@code strip} is {@code true} and {@code prefix} is non-null, the {@code prefix} will * be stripped from the property key in the returned {@code Map}. * </p> * * @param sources {@code MutablePropertySources} whose key/value pairs are enumerated and placed into the returned * {@code Map} * @param prefix only include properties whose key starts with the supplied prefix, may be {@code null} * @param strip if {@code true}, strip the {@code prefix} off of the property key in the returned {@code Map} * @return a {@code Map} containing the enumerated property keys and values from {@code sources} */ public static Map<String, Object> asMap(MutablePropertySources sources, String prefix, boolean strip) { Map<String, Object> props = new HashMap<>(); filterEnumerablePropertySources(sources).forEach(source -> { if (!(source instanceof EnumerablePropertySource)) { return; } Stream.of(((EnumerablePropertySource)source).getPropertyNames()) .filter(propName -> prefix == null || propName.startsWith(prefix)) .peek(propName -> LOG.debug( "Found kafka property prefix: [{}], property name: [{}]", prefix, propName)) .collect(Collectors.toMap( propName -> (prefix == null || !strip || !propName.startsWith(prefix)) ? propName : propName.substring(prefix.length()), source::getProperty, (val1, val2) -> { LOG.debug("Merging kafka property value [{}], [{}]: [{}] wins", val1, val2, val2); return val2; }, () -> props )) .forEach((key, value) -> LOG.debug("Kafka property: [{}]=[{}]", key, (isNullValue(value)) ? "null" : value)); }); return props; }
/** * Filters the supplied {@code MutablePropertySources} for instances of {@code EnumerablePropertySource}, and * returns a new {@code MutablePropertySource} containing <em>only</em> {@code EnumerablePropertySource} sources. * * @param sources property sources that may contain instances of {@code EnumerablePropertySource} * @return property sources that contain <em>only</em> {@code EnumerablePropertySource} */ public static MutablePropertySources filterEnumerablePropertySources(MutablePropertySources sources) { MutablePropertySources enumerableSources = new MutablePropertySources(); sources.forEach(source -> { if (source instanceof EnumerablePropertySource) { enumerableSources.addLast(source); } }); return enumerableSources; }
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); }
@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)); }
/** * @since 4.1.5 */ @Test @SuppressWarnings("rawtypes") public void addInlinedPropertiesToEnvironmentWithEmptyProperty() { ConfigurableEnvironment environment = new MockEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME); assertEquals(0, propertySources.size()); addInlinedPropertiesToEnvironment(environment, new String[] { " " }); assertEquals(1, propertySources.size()); assertEquals(0, ((Map) propertySources.iterator().next().getSource()).size()); }
private void registerPropertySources( Collection<? extends PropertySource<?>> propertySources, MutablePropertySources mutablePropertySources) { for (PropertySource<?> vaultPropertySource : propertySources) { if (propertySources.contains(vaultPropertySource.getName())) { continue; } mutablePropertySources.addLast(vaultPropertySource); } }
public static Map<String, Object> getAllProperties(String prefix){ init(); if(environment == null)return null; MutablePropertySources propertySources = ((ConfigurableEnvironment)environment).getPropertySources(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); for (PropertySource<?> source : propertySources) { if(source.getName().startsWith("servlet") || source.getName().startsWith("system")){ continue; } if (source instanceof EnumerablePropertySource) { for (String name : ((EnumerablePropertySource<?>) source) .getPropertyNames()) { boolean match = StringUtils.isEmpty(prefix); if(!match){ match = name.startsWith(prefix); } if(match){ Object value = source.getProperty(name); if(value != null){ properties.put(name, value); } } } } } return Collections.unmodifiableMap(properties); }
/** * Create a new {@link PropertySourceLoader} instance backed by the specified * {@link MutablePropertySources}. * @param propertySources the destination property sources */ public PropertySourcesLoader(MutablePropertySources propertySources) { Assert.notNull(propertySources, "PropertySources must not be null"); this.propertySources = propertySources; this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader()); }
private void addJsonPropertySource(ConfigurableEnvironment environment, PropertySource<?> source) { MutablePropertySources sources = environment.getPropertySources(); String name = findPropertySource(sources); if (sources.contains(name)) { sources.addBefore(name, source); } else { sources.addFirst(source); } }
private String findPropertySource(MutablePropertySources sources) { if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) && sources .contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { return StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME; } return StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME; }
private PropertySources deducePropertySources() { PropertySourcesPlaceholderConfigurer configurer = getSinglePropertySourcesPlaceholderConfigurer(); if (configurer != null) { // Flatten the sources into a single list so they can be iterated return new FlatPropertySources(configurer.getAppliedPropertySources()); } if (this.environment instanceof ConfigurableEnvironment) { MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment) .getPropertySources(); return new FlatPropertySources(propertySources); } // empty, so not very useful, but fulfils the contract return new MutablePropertySources(); }
private MutablePropertySources getFlattened() { MutablePropertySources result = new MutablePropertySources(); for (PropertySource<?> propertySource : this.propertySources) { flattenPropertySources(propertySource, result); } return result; }
private void flattenPropertySources(PropertySource<?> propertySource, MutablePropertySources result) { Object source = propertySource.getSource(); if (source instanceof ConfigurableEnvironment) { ConfigurableEnvironment environment = (ConfigurableEnvironment) source; for (PropertySource<?> childSource : environment.getPropertySources()) { flattenPropertySources(childSource, result); } } else { result.addLast(propertySource); } }
private void addConfigurationProperties(MutablePropertySources sources) { List<PropertySource<?>> reorderedSources = new ArrayList<PropertySource<?>>(); for (PropertySource<?> item : sources) { reorderedSources.add(item); } addConfigurationProperties( new ConfigurationPropertySources(reorderedSources)); }
private void addConfigurationProperties( ConfigurationPropertySources configurationSources) { MutablePropertySources existingSources = this.environment .getPropertySources(); if (existingSources.contains(DEFAULT_PROPERTIES)) { existingSources.addBefore(DEFAULT_PROPERTIES, configurationSources); } else { existingSources.addLast(configurationSources); } }