类org.springframework.boot.context.properties.source.ConfigurationPropertyName源码实例Demo

下面列出了怎么用org.springframework.boot.context.properties.source.ConfigurationPropertyName的API类实例代码及写法,或者点击链接到github查看源代码。

public static void main(String[] args) throws Exception {
    // 查找 adapt(CharSequence, char) 静态方法
    Method method = ReflectionUtils.findMethod(ConfigurationPropertyName.class, "adapt", CharSequence.class, char.class);
    // 设置非 public 可访问
    method.setAccessible(true);
    // 执行 adapt 静态方法
    ConfigurationPropertyName configurationPropertyName = (ConfigurationPropertyName)
            method.invoke(null, "user.HOMEP-AGE", '.');
    // 获取 "." 分割后的元素数量
    int numberOfElements = configurationPropertyName.getNumberOfElements();
    for (int i = 0; i < numberOfElements; i++) {
        // 原始格式
        String originalElement = configurationPropertyName.getElement(i, ConfigurationPropertyName.Form.ORIGINAL);
        // 统一格式
        String uniformElement = configurationPropertyName.getElement(i, ConfigurationPropertyName.Form.UNIFORM);
        // 输出
        System.out.printf("配置属性名['%s']的元素[%d] 原始格式 : '%s' , 统一格式 : '%s' \n",
                configurationPropertyName, i, originalElement, uniformElement);
    }
}
 
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();
}
 
public static void main(String[] args) {
    // 配置属性名抽象:ConfigurationPropertyName
    ConfigurationPropertyName configurationPropertyName = ConfigurationPropertyName.of("a.b.c");
    // 获取 "." 分割后的元素数量
    int numberOfElements = configurationPropertyName.getNumberOfElements();
    for (int i = 0; i < numberOfElements; i++) {
        // 获取劈断大小
        int size = i + 1;
        ConfigurationPropertyName chopped = configurationPropertyName.chop(size);
        // 输出
        System.out.printf("劈断[大小 : %d]的配置属性名['%s'] 是否为配置属性名['%s'] 的父属性名 : %b , 祖属性名 : %b \n",
                size, chopped, configurationPropertyName, chopped.isParentOf(configurationPropertyName),
                chopped.isAncestorOf(configurationPropertyName)
        );
    }
}
 
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();
}
 
@Override
public BindHandler apply(BindHandler bindHandler) {
	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
									Bindable<T> target, BindContext context) {
			final String configName = name.toString();
			if (configName.contains("use") && configName.contains("native") &&
					(configName.contains("encoding") || configName.contains("decoding"))) {
				BindResult<T> result = context.getBinder().bind(name, target);
				if (result.isBound()) {
					if (configName.contains("encoding")) {
						EncodingDecodingBindAdviceHandler.this.encodingSettingProvided = true;
					}
					else {
						EncodingDecodingBindAdviceHandler.this.decodingSettingProvided = true;
					}
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
@Override
public BindHandler apply(BindHandler bindHandler) {


	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
				Bindable<T> target, BindContext context) {
			ConfigurationPropertyName defaultName = getDefaultName(name);
			if (defaultName != null) {
				BindResult<T> result = context.getBinder().bind(defaultName, target);
				if (result.isBound()) {
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
private ConfigurationPropertyName getDefaultName(ConfigurationPropertyName name) {
	for (Map.Entry<ConfigurationPropertyName, ConfigurationPropertyName> mapping : this.mappings
			.entrySet()) {
		ConfigurationPropertyName from = mapping.getKey();
		ConfigurationPropertyName to = mapping.getValue();
		if ((from.isAncestorOf(name)
				&& name.getNumberOfElements() > from.getNumberOfElements())) {
			ConfigurationPropertyName defaultName = to;
			for (int i = from.getNumberOfElements() + 1; i < name
					.getNumberOfElements(); i++) {
				defaultName = defaultName.append(name.getElement(i, Form.UNIFORM));
			}
			return defaultName;
		}
	}
	return null;
}
 
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
@NotNull
private Optional<ConfigurationPropertyName> toConfigurationName(String key) {
    try {
        return Optional.of(ConfigurationPropertyName.of(key));
    } catch (InvalidConfigurationPropertyNameException e) {
        return Optional.empty();
    }
}
 
@Override
//Spring resolves configuration properties using a configurable property resolver (resolves --prop=${VAR} replaces VAR from an environment variable of the same name.)
//The value provided from the configurable property itself or the property source is not resolved, so we have to get the final value from a resolver.
//Theoretically, this resolver should be bound to the property source, but this current method at least gets the final resolved value. - jp
public String getValue(final String key) {
    return toConfigurationProperty(key)
               .map(ConfigurationProperty::getName)
               .map(ConfigurationPropertyName::toString)
               .map(configurablePropertyResolver::getProperty)
               .map(Object::toString)
               .orElse(null);
}
 
private static void displayElementForm(String propertyName) {
    // 配置属性名抽象:ConfigurationPropertyName
    ConfigurationPropertyName configurationPropertyName = ConfigurationPropertyName.of(propertyName);
    // 获取 "." 分割后的元素数量
    int numberOfElements = configurationPropertyName.getNumberOfElements();
    for (int i = 0; i < numberOfElements; i++) {
        // 原始格式
        String originalElement = configurationPropertyName.getElement(i, ConfigurationPropertyName.Form.ORIGINAL);
        // 统一格式
        String uniformElement = configurationPropertyName.getElement(i, ConfigurationPropertyName.Form.UNIFORM);
        // 输出
        System.out.printf("配置属性名['%s']的元素[%d] 原始格式 : '%s' , 统一格式 : '%s' \n",
                configurationPropertyName, i, originalElement, uniformElement);
    }
}
 
public static void main(String[] args) {
//        ConfigurationPropertyName one = ConfigurationPropertyName.of("user.home-page");
//        ConfigurationPropertyName aonther = ConfigurationPropertyName.of("user.homepage");
//        System.out.printf("配置属性名['%s'] 与 配置属性名['%s'] 相等 : %b", one, aonther, one.equals(aonther));

        // 错误配置属性名,仅允许小写字母 "a-z"、"0-9" 以及 "-"(横划线)
        ConfigurationPropertyName.of("user.HOMEP-AGE");
    }
 
public static void main(String[] args) {

        MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource();

        propertySource.put("userName", "Mercy");
        propertySource.put("user-id", 1);
        propertySource.put("user_id", 1);

        propertySource.stream().map(name -> name.getLastElement(ConfigurationPropertyName.Form.UNIFORM))
                .forEach(System.out::println);
    }
 
源代码15 项目: teiid-spring-boot   文件: XADataSourceBuilder.java
private void bindXaProperties(Bindable<XADataSource> target) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(
            this.properties);
    ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
    aliases.addAliases("url", "jdbc-url");
    aliases.addAliases("username", "user");
    aliases.addAliases("portNumber", "port");
    aliases.addAliases("serverName", "server");
    aliases.addAliases("databaseName", "database");

    Binder binder = new Binder(source.withAliases(aliases));
    binder.bind(ConfigurationPropertyName.EMPTY, target);
}
 
@Bean
public MappingsProvider kafkaExtendedPropertiesDefaultMappingsProvider() {
	return () -> {
		Map<ConfigurationPropertyName, ConfigurationPropertyName> mappings = new HashMap<>();
		mappings.put(
				ConfigurationPropertyName.of("spring.cloud.stream.kafka.bindings"),
				ConfigurationPropertyName.of("spring.cloud.stream.kafka.default"));
		mappings.put(
				ConfigurationPropertyName.of("spring.cloud.stream.kafka.streams"),
				ConfigurationPropertyName
						.of("spring.cloud.stream.kafka.streams.default"));
		return mappings;
	};
}
 
@Bean
public MappingsProvider rabbitExtendedPropertiesDefaultMappingsProvider() {
	return () -> {
		Map<ConfigurationPropertyName, ConfigurationPropertyName> mappings = new HashMap<>();
		mappings.put(
				ConfigurationPropertyName.of("spring.cloud.stream.rabbit.bindings"),
				ConfigurationPropertyName.of("spring.cloud.stream.rabbit.default"));
		return mappings;
	};
}
 
源代码18 项目: spring-cloud-stream   文件: BindingHandlerAdvise.java
BindingHandlerAdvise(
		Map<ConfigurationPropertyName, ConfigurationPropertyName> additionalMappings) {
	this.mappings = new LinkedHashMap<>();
	this.mappings.put(ConfigurationPropertyName.of("spring.cloud.stream.bindings"),
			ConfigurationPropertyName.of("spring.cloud.stream.default"));
	if (!CollectionUtils.isEmpty(additionalMappings)) {
		this.mappings.putAll(additionalMappings);
	}
}
 
@Bean
public BindingHandlerAdvise BindingHandlerAdvise(
		@Nullable MappingsProvider[] providers) {
	Map<ConfigurationPropertyName, ConfigurationPropertyName> additionalMappings = new HashMap<>();
	if (!ObjectUtils.isEmpty(providers)) {
		for (int i = 0; i < providers.length; i++) {
			MappingsProvider mappingsProvider = providers[i];
			additionalMappings.putAll(mappingsProvider.getDefaultMappings());
		}
	}
	return new BindingHandlerAdvise(additionalMappings);
}
 
源代码20 项目: ByteJTA   文件: DataSourceSpiBuilder.java
private void bind(XADataSource result) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	aliases.addAliases("url", "jdbc-url");
	aliases.addAliases("username", "user");
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
源代码21 项目: Milkomeda   文件: DataSourceFactory.java
@SuppressWarnings("rawtypes")
private void bind(DataSource result, Map properties) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source.withAliases(ALIASES));
    binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
@Override
public Boolean hasKey(final String key) {
    Optional<ConfigurationPropertyName> configurationPropertyName = toConfigurationName(key);
    return configurationPropertyName.filter(propertyName -> propertySource.getConfigurationProperty(propertyName) != null).isPresent();
}
 
@Override
public Set<String> getKeys() {
    return Bds.of(propertySource).map(ConfigurationPropertyName::toString).toSet();
}
 
@Override
public Object onFailure(ConfigurationPropertyName name, Bindable<?> target,
        BindContext context, Exception error) throws Exception {
    throw new  MangoAutoConfigException(error);
}
 
@Bean
public MappingsProvider pubSubExtendedPropertiesDefaultMappingsProvider() {
	return () -> Collections.singletonMap(
			ConfigurationPropertyName.of("spring.cloud.stream.gcp.pubsub.bindings"),
			ConfigurationPropertyName.of("spring.cloud.stream.gcp.pubsub.default"));
}
 
源代码26 项目: ByteJTA   文件: DataSourceCciBuilder.java
private void bind(DataSource dataSource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(dataSource));
}
 
源代码27 项目: spring-cloud-stream   文件: BindingHandlerAdvise.java
Map<ConfigurationPropertyName, ConfigurationPropertyName> getDefaultMappings(); 
 类所在包
 类方法
 同包方法