Java Code Examples for org.springframework.boot.context.properties.source.ConfigurationPropertySources

The following examples show how to use org.springframework.boot.context.properties.source.ConfigurationPropertySources. These examples are extracted from open source projects. 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
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 2
@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 3
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 4
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 5
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 6
@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 7
Source Project: loc-framework   Source File: PrefixPropertyCondition.java    License: MIT License 6 votes vote down vote up
@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 8
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 9
@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 10
@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
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 12
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 13
@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 14
Source Project: spring-javaformat   Source File: SpringApplication.java    License: Apache License 2.0 5 votes vote down vote up
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 15
@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 16
@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 17
@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 18
@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
@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 20
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 21
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 22
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 23
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 24
private Iterable<ConfigurationPropertySource> getConfigurationPropertySources() {
  return ConfigurationPropertySources.from(this.propertySources);
}
 
Example 25
private static Iterable<ConfigurationPropertySource> getConfigurationPropertySources(PropertySources propertySources) {
    return ConfigurationPropertySources.from(propertySources);
}
 
Example 26
Source Project: loc-framework   Source File: LocBaseAutoConfiguration.java    License: MIT License 4 votes vote down vote up
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"));
}