org.springframework.boot.context.properties.source.ConfigurationPropertySources Java Examples
The following examples show how to use
org.springframework.boot.context.properties.source.ConfigurationPropertySources.
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: BinderBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 7 votes |
public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(BinderBootstrap.class) .web(WebApplicationType.NONE) // 非 Web 应用 .properties("user.city.postCode=0731") .run(args); ConfigurableEnvironment environment = context.getEnvironment(); // 从 Environment 中获取 ConfigurationPropertySource 集合 Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment); // 构造 Binder 对象,并使用 ConfigurationPropertySource 集合作为配置源 Binder binder = new Binder(sources); // 构造 ConfigurationPropertyName(Spring Boot 2.0 API) ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code"); // 构造 Bindable 对象,包装 postCode Bindable<String> postCodeBindable = Bindable.of(String.class); BindResult<String> result = binder.bind(propertyName, postCodeBindable); String postCode = result.get(); System.out.println("postCode = " + postCode); // 关闭上下文 context.close(); }
Example #2
Source File: ExternalizedConfigurationBinderBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 7 votes |
public static void main(String[] args) throws IOException { // application.properties 文件资源 classpath 路径 String location = "application.properties"; // 编码化的 Resource 对象(解决乱码问题) EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8"); // 加载 application.properties 文件,转化为 Properties 对象 Properties properties = PropertiesLoaderUtils.loadProperties(resource); // 创建 Properties 类型的 PropertySource PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties); // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合 Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource); // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力) Binder binder = new Binder(propertySources, null, conversionService()); // 执行绑定,返回绑定结果 BindResult<User> bindResult = binder.bind("user", User.class); // 获取绑定对象 User user = bindResult.get(); // 输出结果 System.out.println(user); }
Example #3
Source File: SpringConfigurationPropertySource.java From synopsys-detect with Apache License 2.0 | 6 votes |
public static List<SpringConfigurationPropertySource> fromConfigurableEnvironment(ConfigurableEnvironment configurableEnvironment, boolean ignoreUnknown) { List<ConfigurationPropertySource> sources = Bds.listOf(ConfigurationPropertySources.get(configurableEnvironment)); return Bds.of(sources).map(it -> { if (IterableConfigurationPropertySource.class.isAssignableFrom(it.getClass())) { return getPropertySource(configurableEnvironment, ignoreUnknown, it); } else if (RandomValuePropertySource.class.isAssignableFrom(it.getUnderlyingSource().getClass())) { //We know an underlying random source can't be iterated but we don't care. It can't give a list of known keys. return null; } else { if (ignoreUnknown) { return null; } else { throw new RuntimeException( new UnknownSpringConfigurationException("Unknown spring configuration type. We may be unable to find property information from it correctly. Likely a new configuration property source should be tested against. ")); } } }).filterNotNull().toList(); }
Example #4
Source File: AbstractExtendedBindingProperties.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private void bindToDefault(String binding) { T extendedBindingPropertiesTarget = (T) BeanUtils .instantiateClass(this.getExtendedPropertiesEntryClass()); Binder binder = new Binder( ConfigurationPropertySources .get(this.applicationContext.getEnvironment()), new PropertySourcesPlaceholdersResolver( this.applicationContext.getEnvironment()), IntegrationUtils.getConversionService( this.applicationContext.getBeanFactory()), null); binder.bind(this.getDefaultsPrefix(), Bindable.ofInstance(extendedBindingPropertiesTarget)); this.bindings.put(binding, extendedBindingPropertiesTarget); }
Example #5
Source File: JasyptEncryptorConfigurationProperties.java From jasypt-spring-boot with MIT License | 6 votes |
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; }
Example #6
Source File: PrefixPropertyCondition.java From loc-framework with MIT License | 6 votes |
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String prefix = (String) attribute(metadata, "prefix"); Class<?> value = (Class<?>) attribute(metadata, "value"); ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment(); try { new Binder(ConfigurationPropertySources.from(environment.getPropertySources())) .bind(prefix, Bindable.of(value)) .orElseThrow( () -> new FatalBeanException("Could not bind DataSourceSettings properties")); return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix)); } catch (Exception e) { //ignore } return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix)); }
Example #7
Source File: OAuth2AutoConfigurationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 6 votes |
@Test public void testCanUseClientCredentialsWithEnableOAuth2Client() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues .of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials") .applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); // The primary context is fine (not session scoped): OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class); assertThat(bean.getAccessTokenRequest()).isNotNull(); assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1); // Kind of a bug (should ideally be 1), but the cause is in Spring OAuth2 (there // is no need for the extra session-scoped bean). What this test proves is that // even if the user screws up and does @EnableOAuth2Client for client // credentials, // it will still just about work (because of the @Primary annotation on the // Boot-created instance of OAuth2ClientContext). assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2); }
Example #8
Source File: ConfigurationPropertySourcesBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 6 votes |
public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder( ConfigurationPropertySourcesBootstrap.class) .properties("user.city.postCode=0571") .web(WebApplicationType.NONE) // 非 Web 应用 .run(args); ConfigurableEnvironment environment = context.getEnvironment(); // 从 Environment 中获取 ConfigurationPropertySource 集合 Iterable<ConfigurationPropertySource> configurationPropertySources = ConfigurationPropertySources.get(environment); // 构造 ConfigurationPropertyName(Spring Boot 2.0 API) ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code"); // 迭代 ConfigurationPropertySource configurationPropertySources.forEach(configurationPropertySource -> { // 通过 ConfigurationPropertyName 获取 ConfigurationProperty ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(propertyName); if (configurationProperty != null) { String postCode = (String) configurationProperty.getValue(); System.out.println("postCode = " + postCode + " , from : " + configurationProperty.getOrigin()); } }); // 关闭上下文 context.close(); }
Example #9
Source File: ApplicationPropertiesTests.java From github-release-notes-generator with Apache License 2.0 | 6 votes |
@Test public void loadYaml() throws Exception { YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); List<PropertySource<?>> yaml = yamlLoader.load("application", new ClassPathResource("test-application.yml", getClass())); Binder binder = new Binder(ConfigurationPropertySources.from(yaml)); ApplicationProperties properties = binder.bind("releasenotes", ApplicationProperties.class).get(); Github github = properties.getGithub(); assertThat(github.getUsername()).isEqualTo("testuser"); assertThat(github.getPassword()).isEqualTo("testpass"); assertThat(github.getOrganization()).isEqualTo("testorg"); assertThat(github.getRepository()).isEqualTo("testrepo"); List<Section> sections = properties.getSections(); assertThat(sections.get(0).getTitle()).isEqualTo("New Features"); assertThat(sections.get(0).getEmoji()).isEqualTo(":star:"); assertThat(sections.get(0).getLabels()).containsExactly("enhancement"); }
Example #10
Source File: SpringCloudDubboAutoConfiguration.java From spring-cloud-dubbo with Apache License 2.0 | 5 votes |
@ConditionalOnProperty(name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnClass(ConfigurationPropertySources.class) @Bean public FeignClientToDubboProviderBeanPostProcessor feignClientToDubboProviderBeanPostProcessor(Environment environment) { Set<String> packagesToScan = environment.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); return new FeignClientToDubboProviderBeanPostProcessor(packagesToScan); }
Example #11
Source File: ConsulDiscoveryClientConfigurationTests.java From spring-cloud-consul with Apache License 2.0 | 5 votes |
private void setupContext(Class<?>... config) { ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class); for (Class<?> value : config) { this.context.register(value); } this.context.refresh(); }
Example #12
Source File: EurekaClientAutoConfigurationTests.java From spring-cloud-netflix with Apache License 2.0 | 5 votes |
private void setupContext(Class<?>... config) { ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.register(PropertyPlaceholderAutoConfiguration.class, DiscoveryClientOptionalArgsConfiguration.class, EurekaDiscoveryClientConfiguration.class); for (Class<?> value : config) { this.context.register(value); } this.context.register(TestConfiguration.class); this.context.refresh(); }
Example #13
Source File: HostInfoEnvironmentPostProcessor.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) { InetUtilsProperties target = new InetUtilsProperties(); ConfigurationPropertySources.attach(environment); Binder.get(environment).bind(InetUtilsProperties.PREFIX, Bindable.ofInstance(target)); try (InetUtils utils = new InetUtils(target)) { return utils.findFirstNonLoopbackHostInfo(); } }
Example #14
Source File: BindingServiceProperties.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
private void bindToDefault(String binding) { BindingProperties bindingPropertiesTarget = new BindingProperties(); Binder binder = new Binder( ConfigurationPropertySources .get(this.applicationContext.getEnvironment()), new PropertySourcesPlaceholdersResolver( this.applicationContext.getEnvironment()), IntegrationUtils.getConversionService( this.applicationContext.getBeanFactory()), null); binder.bind("spring.cloud.stream.default", Bindable.ofInstance(bindingPropertiesTarget)); this.bindings.put(binding, bindingPropertiesTarget); }
Example #15
Source File: SpringCloudAlibabaDubboAutoConfiguration.java From spring-cloud-alibaba-dubbo with Apache License 2.0 | 5 votes |
@ConditionalOnProperty(name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnClass(ConfigurationPropertySources.class) @Bean public FeignClientToDubboProviderBeanPostProcessor feignClientToDubboProviderBeanPostProcessor(Environment environment) { Set<String> packagesToScan = environment.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); return new FeignClientToDubboProviderBeanPostProcessor(packagesToScan); }
Example #16
Source File: EurekaConfigurationListener.java From summerframework with Apache License 2.0 | 5 votes |
private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) { InetUtilsProperties target = new InetUtilsProperties(); ConfigurationPropertySources.attach(environment); Binder.get(environment).bind(InetUtilsProperties.PREFIX, Bindable.ofInstance(target)); try (InetUtils utils = new InetUtils(target)) { return utils.findFirstNonLoopbackHostInfo(); } }
Example #17
Source File: KafkaStreamsBinderSupportAutoConfiguration.java From spring-cloud-stream-binder-kafka with Apache License 2.0 | 5 votes |
@Bean @ConfigurationProperties(prefix = "spring.cloud.stream.kafka.streams.binder") public KafkaStreamsBinderConfigurationProperties binderConfigurationProperties( KafkaProperties kafkaProperties, ConfigurableEnvironment environment, BindingServiceProperties properties, ConfigurableApplicationContext context) throws Exception { final Map<String, BinderConfiguration> binderConfigurations = getBinderConfigurations( properties); for (Map.Entry<String, BinderConfiguration> entry : binderConfigurations .entrySet()) { final BinderConfiguration binderConfiguration = entry.getValue(); final String binderType = binderConfiguration.getBinderType(); if (binderType != null && (binderType.equals(KSTREAM_BINDER_TYPE) || binderType.equals(KTABLE_BINDER_TYPE) || binderType.equals(GLOBALKTABLE_BINDER_TYPE))) { Map<String, Object> binderProperties = new HashMap<>(); this.flatten(null, binderConfiguration.getProperties(), binderProperties); environment.getPropertySources().addFirst( new MapPropertySource(entry.getKey() + "-kafkaStreamsBinderEnv", binderProperties)); Binder binder = new Binder(ConfigurationPropertySources.get(environment), new PropertySourcesPlaceholdersResolver(environment), IntegrationUtils.getConversionService(context.getBeanFactory()), null); final Constructor<KafkaStreamsBinderConfigurationProperties> kafkaStreamsBinderConfigurationPropertiesConstructor = ReflectionUtils.accessibleConstructor(KafkaStreamsBinderConfigurationProperties.class, KafkaProperties.class); final KafkaStreamsBinderConfigurationProperties kafkaStreamsBinderConfigurationProperties = BeanUtils.instantiateClass(kafkaStreamsBinderConfigurationPropertiesConstructor, kafkaProperties); final BindResult<KafkaStreamsBinderConfigurationProperties> bind = binder.bind("spring.cloud.stream.kafka.streams.binder", Bindable.ofInstance(kafkaStreamsBinderConfigurationProperties)); context.getBeanFactory().registerSingleton( entry.getKey() + "-KafkaStreamsBinderConfigurationProperties", bind.get()); } } return new KafkaStreamsBinderConfigurationProperties(kafkaProperties); }
Example #18
Source File: OAuth2AutoConfigurationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 5 votes |
@Test public void authorizationServerWhenUsingJwtConfigurationThenConfiguresJwt() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(AuthorizationServerConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues.of("security.oauth2.authorization.jwt.keyValue:DEADBEEF").applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1); assertThat(countBeans(JwtAccessTokenConverter.class)).isEqualTo(1); }
Example #19
Source File: OAuth2AutoConfigurationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 5 votes |
@Test public void testDisablingAuthorizationServer() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(ResourceServerConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues.of("security.oauth2.resource.jwt.keyValue:DEADBEEF").applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(UserApprovalHandler.class)).isEqualTo(0); assertThat(countBeans(DefaultTokenServices.class)).isEqualTo(1); }
Example #20
Source File: FunctionalConfigurationPropertiesBinder.java From spring-fu with Apache License 2.0 | 5 votes |
public FunctionalConfigurationPropertiesBinder(ConfigurableApplicationContext context) { PropertySources propertySources = new FunctionalPropertySourcesDeducer(context).getPropertySources(); this.context = context; this.binder = new Binder(ConfigurationPropertySources.from(propertySources), new PropertySourcesPlaceholdersResolver(propertySources), null, (registry) -> context.getBeanFactory().copyRegisteredEditorsTo(registry)); }
Example #21
Source File: OAuth2AutoConfigurationTests.java From spring-security-oauth2-boot with Apache License 2.0 | 5 votes |
@Test public void testCanUseClientCredentials() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(TestSecurityConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues .of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials") .applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class); assertThat(bean.getAccessTokenRequest()).isNotNull(); assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1); assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(1); }
Example #22
Source File: DubboRelaxedBinding2AutoConfiguration.java From dubbo-spring-boot-project with Apache License 2.0 | 5 votes |
@Bean(name = BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME) public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) { ConfigurableEnvironment propertyResolver = new AbstractEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { Map<String, Object> dubboScanProperties = getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties)); } }; ConfigurationPropertySources.attach(propertyResolver); return new DelegatingPropertyResolver(propertyResolver); }
Example #23
Source File: SpringApplication.java From spring-javaformat with Apache License 2.0 | 5 votes |
private ConfigurableEnvironment prepareEnvironment( SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment(); configureEnvironment(environment, applicationArguments.getSourceArgs()); listeners.environmentPrepared(environment); bindToSpringApplication(environment); if (this.webApplicationType == WebApplicationType.NONE) { environment = new EnvironmentConverter(getClassLoader()) .convertToStandardEnvironmentIfNecessary(environment); } ConfigurationPropertySources.attach(environment); return environment; }
Example #24
Source File: MangoConfigFactory.java From mango-spring-boot-starter with Apache License 2.0 | 4 votes |
private static Iterable<ConfigurationPropertySource> getConfigurationPropertySources(PropertySources propertySources) { return ConfigurationPropertySources.from(propertySources); }
Example #25
Source File: LocBaseAutoConfiguration.java From loc-framework with MIT License | 4 votes |
protected <T> T resolverSetting(Class<T> clazz, MutablePropertySources propertySources) { return new Binder(ConfigurationPropertySources.from(propertySources)) .bind("loc", Bindable.of(clazz)) .orElseThrow(() -> new FatalBeanException("Could not bind properties")); }
Example #26
Source File: CustomizedConfigurationPropertiesBinder.java From apollo-use-cases with Apache License 2.0 | 4 votes |
private Iterable<ConfigurationPropertySource> getConfigurationPropertySources() { return ConfigurationPropertySources.from(this.propertySources); }