Java源码示例:org.springframework.boot.context.properties.source.ConfigurationPropertyName

示例1
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);
    }
}
 
示例2
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();
}
 
示例3
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)
        );
    }
}
 
示例4
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();
}
 
示例5
@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;
}
 
示例6
@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);
  }
}
 
示例7
@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;
}
 
示例8
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;
}
 
示例9
@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);
  }
}
 
示例10
@NotNull
private Optional<ConfigurationPropertyName> toConfigurationName(String key) {
    try {
        return Optional.of(ConfigurationPropertyName.of(key));
    } catch (InvalidConfigurationPropertyNameException e) {
        return Optional.empty();
    }
}
 
示例11
@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);
}
 
示例12
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);
    }
}
 
示例13
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");
    }
 
示例14
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
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);
}
 
示例16
@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;
	};
}
 
示例17
@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
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);
	}
}
 
示例19
@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
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
@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));
}
 
示例22
@Override
public Boolean hasKey(final String key) {
    Optional<ConfigurationPropertyName> configurationPropertyName = toConfigurationName(key);
    return configurationPropertyName.filter(propertyName -> propertySource.getConfigurationProperty(propertyName) != null).isPresent();
}
 
示例23
@Override
public Set<String> getKeys() {
    return Bds.of(propertySource).map(ConfigurationPropertyName::toString).toSet();
}
 
示例24
@Override
public Object onFailure(ConfigurationPropertyName name, Bindable<?> target,
        BindContext context, Exception error) throws Exception {
    throw new  MangoAutoConfigException(error);
}
 
示例25
@Bean
public MappingsProvider pubSubExtendedPropertiesDefaultMappingsProvider() {
	return () -> Collections.singletonMap(
			ConfigurationPropertyName.of("spring.cloud.stream.gcp.pubsub.bindings"),
			ConfigurationPropertyName.of("spring.cloud.stream.gcp.pubsub.default"));
}
 
示例26
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
Map<ConfigurationPropertyName, ConfigurationPropertyName> getDefaultMappings();