/** * Test if this {@code Profiles} instance <em>matches</em> against the given * active profiles predicate. * @param activeProfiles predicate that tests whether a given profile is * currently active */ booleanmatches(Predicate<String> activeProfiles);
/** * Create a new {@link Profiles} instance that checks for matches against * the given <em>profile strings</em>. * <p>The returned instance will {@linkplain Profiles#matches(Predicate) match} * if any one of the given profile strings matches. * <p>A profile string may contain a simple profile name (for example * {@code "production"}) or a profile expression. A profile expression allows * for more complicated profile logic to be expressed, for example * {@code "production & cloud"}. * <p>The following operators are supported in profile expressions: * <ul> * <li>{@code !} - A logical <em>not</em> of the profile</li> * <li>{@code &} - A logical <em>and</em> of the profiles</li> * <li>{@code |} - A logical <em>or</em> of the profiles</li> * </ul> * <p>Please note that the {@code &} and {@code |} operators may not be mixed * without using parentheses. For example {@code "a & b | c"} is not a valid * expression; it must be expressed as {@code "(a & b) | c"} or * {@code "a & (b | c)"}. * @param profiles the <em>profile strings</em> to include * @return a new {@link Profiles} instance */ static Profiles of(String... profiles){ return ProfilesParser.parse(profiles); }
/** * Set the prefix that placeholders replaced by this resolver must begin with. */ voidsetPlaceholderPrefix(String placeholderPrefix);
/** * Set the suffix that placeholders replaced by this resolver must end with. */ voidsetPlaceholderSuffix(String placeholderSuffix);
/** * Specify the separating character between the placeholders replaced by this * resolver and their associated default value, or {@code null} if no such * special character should be processed as a value separator. */ voidsetValueSeparator(@Nullable String valueSeparator);
/** * Set whether to throw an exception when encountering an unresolvable placeholder * nested within the value of a given property. A {@code false} value indicates strict * resolution, i.e. that an exception will be thrown. A {@code true} value indicates * that unresolvable nested placeholders should be passed through in their unresolved * ${...} form. * <p>Implementations of {@link #getProperty(String)} and its variants must inspect * the value set here to determine correct behavior when property values contain * unresolvable placeholders. * @since 3.2 */ voidsetIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders);
/** * Specify which properties must be present, to be verified by * {@link #validateRequiredProperties()}. */ voidsetRequiredProperties(String... requiredProperties);
/** * Validate that each of the properties specified by * {@link #setRequiredProperties} is present and resolves to a * non-{@code null} value. * @throws MissingRequiredPropertiesException if any of the required * properties are not resolvable. */ voidvalidateRequiredProperties()throws MissingRequiredPropertiesException;
Abstract base class for Environment implementations. Supports the notion of reserved default profile names and enables specifying active and default profiles through the ACTIVE_PROFILES_PROPERTY_NAME and DEFAULT_PROFILES_PROPERTY_NAME properties. Concrete subclasses differ primarily on which PropertySource objects they add by default. AbstractEnvironment adds none. Subclasses should contribute property sources through the protected customizePropertySources(MutablePropertySources) hook, while clients should customize using ConfigurableEnvironment.getPropertySources() and working against the MutablePropertySources API. See ConfigurableEnvironment javadoc for usage examples.
/*Customize the set of PropertySource objects to be searched by this Environment during calls to getProperty(String) and related *methods. *Subclasses that override this method are encouraged to add property sources using MutablePropertySources.addLast(PropertySource) such *that further subclasses may call super.customizePropertySources() with predictable results. For example: */ publicclassLevel1EnvironmentextendsAbstractEnvironment{ @Override protectedvoidcustomizePropertySources(MutablePropertySources propertySources){ super.customizePropertySources(propertySources); // no-op from base class propertySources.addLast(new PropertySourceA(...)); propertySources.addLast(new PropertySourceB(...)); } } publicclassLevel2EnvironmentextendsLevel1Environment{ @Override protectedvoidcustomizePropertySources(MutablePropertySources propertySources){ super.customizePropertySources(propertySources); // add all from superclass propertySources.addLast(new PropertySourceC(...)); propertySources.addLast(new PropertySourceD(...)); } } /** *In this arrangement, properties will be resolved against sources A, B, C, D in that order. That is to say that property source "A" *has precedence over property source "D". If the Level2Environment subclass wished to give property sources C and D higher precedence *than A and B, it could simply call super.customizePropertySources after, rather than before adding its own: */ publicclassLevel2EnvironmentextendsLevel1Environment{ @Override protectedvoidcustomizePropertySources(MutablePropertySources propertySources){ propertySources.addLast(new PropertySourceC(...)); propertySources.addLast(new PropertySourceD(...)); super.customizePropertySources(propertySources); // add all from superclass } } /** *The search order is now C, D, A, B as desired. */
privatefinal List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
/** * Create a new {@link MutablePropertySources} object. */ publicMutablePropertySources(){ }
/** * Create a new {@code MutablePropertySources} from the given propertySources * object, preserving the original order of contained {@code PropertySource} objects. */ publicMutablePropertySources(PropertySources propertySources){ this(); for (PropertySource<?> propertySource : propertySources) { addLast(propertySource); } }
@Override public Iterator<PropertySource<?>> iterator() { returnthis.propertySourceList.iterator(); }
@Override public Spliterator<PropertySource<?>> spliterator() { return Spliterators.spliterator(this.propertySourceList, 0); }
@Override public Stream<PropertySource<?>> stream() { returnthis.propertySourceList.stream(); }
@Override @Nullable public PropertySource<?> get(String name) { int index = this.propertySourceList.indexOf(PropertySource.named(name)); return (index != -1 ? this.propertySourceList.get(index) : null); }
/** * Add the given property source object with highest precedence. */ publicvoidaddFirst(PropertySource<?> propertySource){ removeIfPresent(propertySource); this.propertySourceList.add(0, propertySource); }
/** * Add the given property source object with lowest precedence. */ publicvoidaddLast(PropertySource<?> propertySource){ removeIfPresent(propertySource); this.propertySourceList.add(propertySource); }
/** * Add the given property source object with precedence immediately higher * than the named relative property source. */ publicvoidaddBefore(String relativePropertySourceName, PropertySource<?> propertySource){ assertLegalRelativeAddition(relativePropertySourceName, propertySource); removeIfPresent(propertySource); int index = assertPresentAndGetIndex(relativePropertySourceName); addAtIndex(index, propertySource); }
/** * Add the given property source object with precedence immediately lower * than the named relative property source. */ publicvoidaddAfter(String relativePropertySourceName, PropertySource<?> propertySource){ assertLegalRelativeAddition(relativePropertySourceName, propertySource); removeIfPresent(propertySource); int index = assertPresentAndGetIndex(relativePropertySourceName); addAtIndex(index + 1, propertySource); }
/** * Return the precedence of the given property source, {@code -1} if not found. */ publicintprecedenceOf(PropertySource<?> propertySource){ returnthis.propertySourceList.indexOf(propertySource); }
/** * Remove and return the property source with the given name, {@code null} if not found. * @param name the name of the property source to find and remove */ @Nullable public PropertySource<?> remove(String name) { int index = this.propertySourceList.indexOf(PropertySource.named(name)); return (index != -1 ? this.propertySourceList.remove(index) : null); }
/** * Replace the property source with the given name with the given property source object. * @param name the name of the property source to find and replace * @param propertySource the replacement property source * @throws IllegalArgumentException if no property source with the given name is present * @see #contains */ publicvoidreplace(String name, PropertySource<?> propertySource){ int index = assertPresentAndGetIndex(name); this.propertySourceList.set(index, propertySource); }
/** * Return the number of {@link PropertySource} objects contained. */ publicintsize(){ returnthis.propertySourceList.size(); }
@Override public String toString(){ returnthis.propertySourceList.toString(); }
/** * Ensure that the given property source is not being added relative to itself. */ protectedvoidassertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource){ String newPropertySourceName = propertySource.getName(); if (relativePropertySourceName.equals(newPropertySourceName)) { thrownew IllegalArgumentException( "PropertySource named '" + newPropertySourceName + "' cannot be added relative to itself"); } }
/** * Remove the given property source if it is present. */ protectedvoidremoveIfPresent(PropertySource<?> propertySource){ this.propertySourceList.remove(propertySource); }
/** * Add the given property source at a particular index in the list. */ privatevoidaddAtIndex(int index, PropertySource<?> propertySource){ removeIfPresent(propertySource); this.propertySourceList.add(index, propertySource); }
/** * Assert that the named property source is present and return its index. * @param name {@linkplain PropertySource#getName() name of the property source} to find * @throws IllegalArgumentException if the named property source is not present */ privateintassertPresentAndGetIndex(String name){ int index = this.propertySourceList.indexOf(PropertySource.named(name)); if (index == -1) { thrownew IllegalArgumentException("PropertySource named '" + name + "' does not exist"); } return index; }
/** * Create a new {@code PropertySource} with the given name and source object. */ publicPropertySource(String name, T source){ Assert.hasText(name, "Property source name must contain at least one character"); Assert.notNull(source, "Property source must not be null"); this.name = name; this.source = source; }
/** * Create a new {@code PropertySource} with the given name and with a new * {@code Object} instance as the underlying source. * <p>Often useful in testing scenarios when creating anonymous implementations * that never query an actual source but rather return hard-coded values. */ @SuppressWarnings("unchecked") publicPropertySource(String name){ this(name, (T) new Object()); }
/** * Return the name of this {@code PropertySource}. */ public String getName(){ returnthis.name; }
/** * Return the underlying source object for this {@code PropertySource}. */ public T getSource(){ returnthis.source; }
/** * Return whether this {@code PropertySource} contains the given name. * <p>This implementation simply checks for a {@code null} return value * from {@link #getProperty(String)}. Subclasses may wish to implement * a more efficient algorithm if possible. * @param name the property name to find */ publicbooleancontainsProperty(String name){ return (getProperty(name) != null); }
/** * Return the value associated with the given name, * or {@code null} if not found. * @param name the property to find * @see PropertyResolver#getRequiredProperty(String) */ @Nullable publicabstract Object getProperty(String name);
/** * This {@code PropertySource} object is equal to the given object if: * <ul> * <li>they are the same instance * <li>the {@code name} properties for both objects are equal * </ul> * <p>No properties other than {@code name} are evaluated. */ @Override publicbooleanequals(Object other){ return (this == other || (other instanceof PropertySource && ObjectUtils.nullSafeEquals(this.name, ((PropertySource<?>) other).name))); }
/** * Return a hash code derived from the {@code name} property * of this {@code PropertySource} object. */ @Override publicinthashCode(){ return ObjectUtils.nullSafeHashCode(this.name); }
/** * Produce concise output (type and name) if the current log level does not include * debug. If debug is enabled, produce verbose output including the hash code of the * PropertySource instance and every name/value property pair. * <p>This variable verbosity is useful as a property source such as system properties * or environment variables may contain an arbitrary number of property pairs, * potentially leading to difficult to read exception and log messages. * @see Log#isDebugEnabled() */ @Override public String toString(){ if (logger.isDebugEnabled()) { return getClass().getSimpleName() + "@" + System.identityHashCode(this) + " {name='" + this.name + "', properties=" + this.source + "}"; } else { return getClass().getSimpleName() + " {name='" + this.name + "'}"; } }
/** * Return a {@code PropertySource} implementation intended for collection comparison purposes only. * <p>Primarily for internal use, but given a collection of {@code PropertySource} objects, may be * used as follows: * <pre class="code"> * {@code List<PropertySource<?>> sources = new ArrayList<PropertySource<?>>(); * sources.add(new MapPropertySource("sourceA", mapA)); * sources.add(new MapPropertySource("sourceB", mapB)); * assert sources.contains(PropertySource.named("sourceA")); * assert sources.contains(PropertySource.named("sourceB")); * assert !sources.contains(PropertySource.named("sourceC")); * }</pre> * The returned {@code PropertySource} will throw {@code UnsupportedOperationException} * if any methods other than {@code equals(Object)}, {@code hashCode()}, and {@code toString()} * are called. * @param name the name of the comparison {@code PropertySource} to be created and returned. */ publicstatic PropertySource<?> named(String name) { returnnew ComparisonPropertySource(name); }
}
这个类的定义很简单,一个 name 名字表示这个PropertySource,还有一个泛型 T 表示实际内部存储的数据结构,虽然是泛型,但是由于在 getProperty 的时候会传入一个 key 所以这个泛型实际上其实还是一个 k-v 的形式的数据结构。
name 的作用就是为了区别,隔离各个 PropertySource。其中定义的 getProperty 也是留给子类自己去实现如何操作获取结果,比如我现在要实现一个最简单的 PropertySource,那就是这个泛型 T 就直接是 HashMap 就好了,getProperty 直接就是 Map.get。
@Override public ConfigurableConversionService getConversionService(){ // Need to provide an independent DefaultConversionService, not the // shared DefaultConversionService used by PropertySourcesPropertyResolver. ConfigurableConversionService cs = this.conversionService; if (cs == null) { synchronized (this) { cs = this.conversionService; if (cs == null) { cs = new DefaultConversionService(); this.conversionService = cs; } } } return cs; }
@Override publicvoidsetConversionService(ConfigurableConversionService conversionService){ Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; }
@Nullable protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType){ if (targetType == null) { return (T) value; } ConversionService conversionServiceToUse = this.conversionService; if (conversionServiceToUse == null) { // Avoid initialization of shared DefaultConversionService if // no standard type conversion is needed in the first place... if (ClassUtils.isAssignableValue(targetType, value)) { return (T) value; } conversionServiceToUse = DefaultConversionService.getSharedInstance(); } return conversionServiceToUse.convert(value, targetType); } }
@Override @Nullable public String getProperty(String key){ return getProperty(key, String.class); }
@Override public String getProperty(String key, String defaultValue){ String value = getProperty(key); return (value != null ? value : defaultValue); }
@Override public <T> T getProperty(String key, Class<T> targetType, T defaultValue){ T value = getProperty(key, targetType); return (value != null ? value : defaultValue); }
/** * Create a new resolver against the given property sources. * @param propertySources the set of {@link PropertySource} objects to use */ publicPropertySourcesPropertyResolver(@Nullable PropertySources propertySources){ this.propertySources = propertySources; }
@Override publicbooleancontainsProperty(String key){ if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { if (propertySource.containsProperty(key)) { returntrue; } } } returnfalse; }