@Bean @Order(-1) PropertySource dispacherPropertySource() throws IOException { YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); // profile null is default PropertySource propertySource = loader.load("dispachers", new ClassPathResource("dispatch.yml"),null); env.getPropertySources().addLast(propertySource); return propertySource; }
@Override public PropertySource<?> locate(final Environment environment) { final AmazonDynamoDBClient amazonDynamoDBClient = getAmazonDynamoDbClient(environment); createSettingsTable(amazonDynamoDBClient, false); final ScanRequest scan = new ScanRequest(TABLE_NAME); LOGGER.debug("Scanning table with request [{}]", scan); final ScanResult result = amazonDynamoDBClient.scan(scan); LOGGER.debug("Scanned table with result [{}]", scan); final Properties props = new Properties(); result.getItems() .stream() .map(DynamoDbCloudConfigBootstrapConfiguration::retrieveSetting) .forEach(p -> props.put(p.getKey(), p.getValue())); return new PropertiesPropertySource(getClass().getSimpleName(), props); }
@Override public PropertySource<?> locate(final Environment environment) { final Properties props = new Properties(); try { final JdbcCloudConnection connection = new JdbcCloudConnection(environment); final DataSource dataSource = Beans.newDataSource(connection); final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final List<Map<String, Object>> rows = jdbcTemplate.queryForList(connection.getSql()); for (final Map row : rows) { props.put(row.get("name"), row.get("value")); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return new PropertiesPropertySource(getClass().getSimpleName(), props); }
@SuppressWarnings("unchecked") @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { if (cloud == null) { return; } for (ServiceInfo serviceInfo : cloud.getServiceInfos()) { if (serviceInfoType.isAssignableFrom(serviceInfo.getClass())) { PropertySource<?> propertySource = toPropertySource((T) serviceInfo); event.getEnvironment().getPropertySources().addFirst(propertySource); } } }
protected void mergePropertySource() throws Exception { if (this.environment != null) { this.addLast(new PropertySource<Environment>(PropertySourcesPlaceholderConfigurer.ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { public String getProperty(String key) { return this.source.getProperty(key); } }); } else { logger.warn("The injected environment was null!"); } if (this.locations != null && this.locations.length > 0) { Properties localProperties = new Properties(); loadProperties(localProperties); PropertySource<?> localPropertySource = new PropertiesPropertySource(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, localProperties); if (this.localOverride) { this.addFirst(localPropertySource); } else { this.addLast(localPropertySource); } } }
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 void run(String... args) throws Exception { StringBuilder sb = new StringBuilder(); for (String option : args) { sb.append(" ").append(option); } sb = sb.length() == 0 ? sb.append("No Options Specified") : sb; logger.info(String.format("App launched with following arguments: %s", sb.toString())); PropertySource<?> ps = new SimpleCommandLinePropertySource(args); String appUrl = (String) ps.getProperty("appurl"); if (appUrl != null) logger.info(String.format("Command-line appurl is %s", appUrl)); String applicationPropertyUrl = environment.getProperty("spring.application.url"); logger.info(String.format("Current Spring Social ApplicationUrl is %s", applicationPropertyUrl)); String applicationVersion = environment.getProperty("nixmash.blog.mvc.version"); logger.info(String.format("NixMash MVC Application Version: %s", applicationVersion)); }
@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 PropertySource<?> locate(Environment environment) { if (!this.enabled) { return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap()); } Map<String, Object> config; try { GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment(); Assert.notNull(googleConfigEnvironment, "Configuration not in expected format."); config = googleConfigEnvironment.getConfig(); } catch (Exception e) { String message = String.format("Error loading configuration for %s/%s_%s", this.projectId, this.name, this.profile); throw new RuntimeException(message, e); } return new MapPropertySource(PROPERTY_SOURCE_NAME, config); }
public static Properties findProps(ConfigurableEnvironment env, String prefix){ Properties props = new Properties(); for (PropertySource<?> source : env.getPropertySources()) { if (source instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source; for (String name : enumerable.getPropertyNames()) { if (name.startsWith(prefix)) { props.putIfAbsent(name, enumerable.getProperty(name)); } } } } return props; }
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)); }
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); } }
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); } }
/** * druid数据源 * @return */ @Bean @ConfigurationProperties(prefix = DB_PREFIX) public DataSource druidDataSource() { Properties dbProperties = new Properties(); Map<String, Object> map = new HashMap<>(); for (Iterator<PropertySource<?>> it = ((AbstractEnvironment) environment).getPropertySources().iterator(); it.hasNext();) { PropertySource<?> propertySource = it.next(); getPropertiesFromSource(propertySource, map); } dbProperties.putAll(map); DruidDataSource dds = null; try { dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProperties); if (null != dds) { dds.init(); } } catch (Exception e) { throw new RuntimeException("load datasource error, dbProperties is :" + dbProperties, e); } return dds; }
private void addPropertySource(String basename, PropertySource<?> source, String profile) { if (source == null) { return; } if (basename == null) { this.propertySources.addLast(source); return; } EnumerableCompositePropertySource group = getGeneric(basename); group.add(source); logger.trace("Adding PropertySource: " + source + " in group: " + basename); if (this.propertySources.contains(group.getName())) { this.propertySources.replace(group.getName(), group); } else { this.propertySources.addFirst(group); } }
@Test public void testPlaceholdersErrorInNonEnumerable() { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); this.propertySources.addFirst(new PropertySource<Object>("application", "STUFF") { @Override public Object getProperty(String name) { return new Object(); } }); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, Collections.singleton("name"))); assertThat(target.getName()).isNull(); }
@Test public void shouldLocatePropertySourcesInEachPathSpecifiedWhenApplicationNameContainsSeveral() { VaultGenericBackendProperties backendProperties = new VaultGenericBackendProperties(); backendProperties.setApplicationName("wintermute,straylight,icebreaker/armitage"); propertySourceLocator = new VaultPropertySourceLocator(operations, new VaultProperties(), VaultPropertySourceLocatorSupport.createConfiguration(backendProperties)); when(configurableEnvironment.getActiveProfiles()) .thenReturn(new String[] { "vermillion", "periwinkle" }); PropertySource<?> propertySource = propertySourceLocator .locate(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"); }
@Test public void shouldLocatePropertySourcesInVaultApplicationContext() { VaultGenericBackendProperties backendProperties = new VaultGenericBackendProperties(); backendProperties.setApplicationName("wintermute"); propertySourceLocator = new VaultPropertySourceLocator(operations, new VaultProperties(), VaultPropertySourceLocatorSupport.createConfiguration(backendProperties)); when(configurableEnvironment.getActiveProfiles()) .thenReturn(new String[] { "vermillion", "periwinkle" }); PropertySource<?> propertySource = propertySourceLocator .locate(configurableEnvironment); assertThat(propertySource).isInstanceOf(CompositePropertySource.class); CompositePropertySource composite = (CompositePropertySource) propertySource; assertThat(composite.getPropertySources()).extracting("name").containsSequence( "secret/wintermute/periwinkle", "secret/wintermute/vermillion", "secret/wintermute"); }
@Test public void testNonEnumeratedPlaceholder() { this.propertySources.addFirst(new PropertySource<String>("another", "baz") { @Override public Object getProperty(String name) { if (name.equals(getSource())) { return "${foo}"; } return null; } }); PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources, (Collection<String>) null, Collections.singleton("baz")); assertThat(propertyValues.getPropertyValue("baz").getValue()).isEqualTo("bar"); }
/** * 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)); } } }
@Test public void shouldCreatePropertySourcesInOrder() { DefaultSecretBackendConfigurer configurer = new DefaultSecretBackendConfigurer(); configurer.add(new MySecondSecretBackendMetadata()); configurer.add(new MyFirstSecretBackendMetadata()); propertySourceLocator = new VaultPropertySourceLocator(operations, new VaultProperties(), configurer); PropertySource<?> propertySource = propertySourceLocator .locate(configurableEnvironment); assertThat(propertySource).isInstanceOf(CompositePropertySource.class); CompositePropertySource composite = (CompositePropertySource) propertySource; assertThat(composite.getPropertySources()).extracting("name") .containsSequence("foo", "bar"); }
private void processNonEnumerablePropertySource(PropertySource<?> source, PropertySourcesPropertyResolver resolver) { // We can only do exact matches for non-enumerable property names, but // that's better than nothing... if (this.nonEnumerableFallbackNames == null) { return; } for (String propertyName : this.nonEnumerableFallbackNames) { if (!source.containsProperty(propertyName)) { continue; } Object value = null; try { value = resolver.getProperty(propertyName, Object.class); } catch (RuntimeException ex) { // Probably could not convert to Object, weird, but ignorable } if (value == null) { value = source.getProperty(propertyName.toUpperCase()); } putIfAbsent(propertyName, value, source); } }
private Condition<ConfigurableEnvironment> matchingPropertySource( final Class<?> propertySourceClass, final String name) { return new Condition<ConfigurableEnvironment>("has property source") { @Override public boolean matches(ConfigurableEnvironment value) { for (PropertySource<?> source : value.getPropertySources()) { if (propertySourceClass.isInstance(source) && (name == null || name.equals(source.getName()))) { return true; } } return false; } }; }
@Override public Map<String, Object> invoke() { Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("profiles", getEnvironment().getActiveProfiles()); 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> map = new LinkedHashMap<String, Object>(); for (String name : enumerable.getPropertyNames()) { map.put(name, sanitize(name, enumerable.getProperty(name))); } result.put(sourceName, map); } } return result; }
@Bean @Order(-1) PropertySource consumerPropertySource() throws IOException { YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); PropertySource propertySource = loader.load("consumers", new ClassPathResource("consumer.yml"),null); env.getPropertySources().addLast(propertySource); return propertySource; }
@Override public PropertySource<?> locate(final Environment environment) { if (environment instanceof ConfigurableEnvironment) { final String sourceName = MongoDbPropertySource.class.getSimpleName(); final CompositePropertySource composite = new CompositePropertySource(sourceName); final MongoDbPropertySource source = new MongoDbPropertySource(sourceName, mongo); composite.addFirstPropertySource(source); return composite; } return null; }
@Override public PropertySource<?> locate(final Environment environment) { this.configurationJasyptDecryptor = new CasConfigurationJasyptDecryptor(environment); final Properties props = new Properties(); loadEmbeddedYamlOverriddenProperties(props, environment); final File configFile = configurationPropertiesEnvironmentManager().getStandaloneProfileConfigurationFile(); if (configFile != null) { loadSettingsFromStandaloneConfigFile(props, configFile); } final File config = configurationPropertiesEnvironmentManager().getStandaloneProfileConfigurationDirectory(); LOGGER.debug("Located CAS standalone configuration directory at [{}]", config); if (config.isDirectory() && config.exists()) { loadSettingsFromConfigurationSources(environment, props, config); } else { LOGGER.warn("Configuration directory [{}] is not a directory or cannot be found at the specific path", config); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Located setting(s) [{}] from [{}]", props.keySet(), config); } else { LOGGER.info("Found and loaded [{}] setting(s) from [{}]", props.size(), config); } return new PropertiesPropertySource("standaloneCasConfigService", props); }
/** * Configure endpoint via property source override. * * @param serviceInfo * @return */ @Override protected PropertySource<?> toPropertySource(VaultServiceInfo serviceInfo) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("spring.cloud.vault.host", serviceInfo.getHost()); properties.put("spring.cloud.vault.port", serviceInfo.getPort()); properties.put("spring.cloud.vault.scheme", serviceInfo.getScheme()); return new MapPropertySource("spring-cloud-vault-connector", properties); }
/** * 返回Environment中的多版本属性源,不存在则创建 * * @param environment * @return */ public static MultiVersionPropertySource getMultiVersionPropertySource(ConfigurableEnvironment environment) { PropertySource<?> multiVersionPropertySource = environment.getPropertySources().get(MULTIVERSION_PROPERTY_SOURCE_NAME); // 不存在多版本属性源,则创建 if (multiVersionPropertySource == null) { multiVersionPropertySource = createMultiVersionPropertySource(); environment.getPropertySources().addLast(multiVersionPropertySource); } return (MultiVersionPropertySource) multiVersionPropertySource; }
public static void main(String[] args) throws Exception { PropertySource commandLineProperties = new SimpleCommandLinePropertySource(args); AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(); context.getEnvironment().getPropertySources().addFirst(commandLineProperties); context.register(ApplicationConfiguration.class); context.refresh(); }
private static boolean doReIndex(String[] args) { PropertySource ps = new SimpleCommandLinePropertySource(args); if (ps.getProperty("reindex") == null) return false; else return Boolean.valueOf(ps.getProperty("reindex").toString()); }
private MapPropertySource findZuulPropertySource(ConfigurableEnvironment environment) { for (PropertySource<?> propertySource : environment.getPropertySources()) { if (propertySource instanceof MapPropertySource) { for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) { if (key.toLowerCase().startsWith(ZUUL_SERVICE_VERSIONS_ROOT)) { return (MapPropertySource) propertySource; } } } } return null; }
@Override protected PropertySource<Map<String, Object>> getPropertySource(PropertySource<Map<String, Object>> propertiesPropertySource) { if (stringEncryptor != null) { //fixme use EncryptablePropertyResolver as bean directly instead of StringEncryptor return new EncryptablePropertySourceWrapper<>(propertiesPropertySource, new DefaultPropertyResolver(stringEncryptor)); } return propertiesPropertySource; }
public List<PropertySource<?>> getPropertySources() { List<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>(); for (Map.Entry<String, List<ResourcePropertySource>> entry : this.propertySources.entrySet()) { propertySources.add(0, collatePropertySources(entry.getKey(), entry.getValue())); } return propertySources; }
private PropertySource<?> collatePropertySources(String name, List<ResourcePropertySource> propertySources) { if (propertySources.size() == 1) { return propertySources.get(0).withName(name); } CompositePropertySource result = new CompositePropertySource(name); for (int i = propertySources.size() - 1; i >= 0; i--) { result.addPropertySource(propertySources.get(i)); } return result; }
/** * {@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; }
@Test public void isSensitiveOverride() throws Exception { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections.<String, Object>singletonMap(this.property + ".sensitive", String.valueOf(!this.sensitive))); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive); }