189 8069 5689

spring中PropertySource类的作用是什么

本篇文章为大家展示了spring中 PropertySource类的作用是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联建站服务项目包括枣庄网站建设、枣庄网站制作、枣庄网页制作以及枣庄网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,枣庄网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到枣庄省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

  • 源码

package org.springframework.core.env;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;


public abstract class PropertySource {

	protected final Log logger = LogFactory.getLog(getClass());

	protected final String name;

	protected final T source;


	/**
	 * Create a new {@code PropertySource} with the given name and source object.
	 * @param name the associated name
	 * @param source the source object
	 */
	public PropertySource(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.
	 * 

Often useful in testing scenarios when creating anonymous implementations  * that never query an actual source but rather return hard-coded values.  */ @SuppressWarnings("unchecked") public PropertySource(String name) { this(name, (T) new Object()); } /**  * Return the name of this {@code PropertySource}.  */ public String getName() { return this.name; } /**  * Return the underlying source object for this {@code PropertySource}.  */ public T getSource() { return this.source; } /**  * Return whether this {@code PropertySource} contains the given name.  * 

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  */ public boolean containsProperty(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 public abstract Object getProperty(String name); /**  * This {@code PropertySource} object is equal to the given object if:  * 

     * 
  • they are the same instance  * 
  • the {@code name} properties for both objects are equal  * 
 * 

No properties other than {@code name} are evaluated.  */ @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof PropertySource && ObjectUtils.nullSafeEquals(getName(), ((PropertySource) other).getName()))); } /**  * Return a hash code derived from the {@code name} property  * of this {@code PropertySource} object.  */ @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(getName()); } /**  * 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.  * 

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='" + getName() + "', properties=" + getSource() + "}"; } else { return getClass().getSimpleName() + " {name='" + getName() + "'}"; } } /**  * Return a {@code PropertySource} implementation intended for collection comparison purposes only.  * 

Primarily for internal use, but given a collection of {@code PropertySource} objects, may be  * used as follows:  *   * {@code List> sources = new ArrayList>();  * 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"));  * }

 * 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.  */ public static PropertySource named(String name) { return new ComparisonPropertySource(name); } /**  * {@code PropertySource} to be used as a placeholder in cases where an actual  * property source cannot be eagerly initialized at application context  * creation time.  For example, a {@code ServletContext}-based property source  * must wait until the {@code ServletContext} object is available to its enclosing  * {@code ApplicationContext}.  In such cases, a stub should be used to hold the  * intended default position/order of the property source, then be replaced  * during context refresh.  * @see org.springframework.context.support.AbstractApplicationContext#initPropertySources()  * @see org.springframework.web.context.support.StandardServletEnvironment  * @see org.springframework.web.context.support.ServletContextPropertySource  */ public static class StubPropertySource extends PropertySource { public StubPropertySource(String name) { super(name, new Object()); } /**  * Always returns {@code null}.  */ @Override @Nullable public String getProperty(String name) { return null; } } /**  * A {@code PropertySource} implementation intended for collection comparison  * purposes.  *  * @see PropertySource#named(String)  */ static class ComparisonPropertySource extends StubPropertySource { private static final String USAGE_ERROR = "ComparisonPropertySource instances are for use with collection comparison only"; public ComparisonPropertySource(String name) { super(name); } @Override public Object getSource() { throw new UnsupportedOperationException(USAGE_ERROR); } @Override public boolean containsProperty(String name) { throw new UnsupportedOperationException(USAGE_ERROR); } @Override @Nullable public String getProperty(String name) { throw new UnsupportedOperationException(USAGE_ERROR); } } }
  • PropertySource 抽象类将一个对象封装成name/value的形式, 方便资源定位,在使用@PropertySource注解的时候,和注解name和value对应

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {

	/**
	 * Indicate the name of this property source. If omitted, the {@link #factory}
	 * will generate a name based on the underlying resource (in the case of
	 * {@link org.springframework.core.io.support.DefaultPropertySourceFactory}:
	 * derived from the resource description through a corresponding name-less
	 * {@link org.springframework.core.io.support.ResourcePropertySource} constructor).
	 * @see org.springframework.core.env.PropertySource#getName()
	 * @see org.springframework.core.io.Resource#getDescription()
	 */
	String name() default "";

	/**
	 * Indicate the resource location(s) of the properties file to be loaded.
	 * 

Both traditional and XML-based properties file formats are supported  * — for example, {@code "classpath:/com/myco/app.properties"}  * or {@code "file:/path/to/file.xml"}.  * 

Resource location wildcards (e.g. **/*.properties) are not permitted;  * each location must evaluate to exactly one {@code .properties} or {@code .xml}  * resource.  * 

${...} placeholders will be resolved against any/all property sources already  * registered with the {@code Environment}. See {@linkplain PropertySource above}  * for examples.  * 

Each location will be added to the enclosing {@code Environment} as its own  * property source, and in the order declared.  */ String[] value();

  • 需要注意的是PropertySource类有两个内部类,StubPropertySource和ComparisonPropertySource; StubPropertySource用于占位,而ComparisonPropertySource则用于比较两个PropertySource. 还有一个named方法,返回ComparisonPropertySource对象.

  1. hashcode是由name生成的,equals是比较name值, 那么现在判断两个PropertySource是否相等,只要判断name值相等就可以了.

  2. 如果没有ComparisonPropertySource的话,判断PropertySource的name值是否等于一个值,需要这样做↓↓↓

Map map1 = new HashMap() {{
    put("a", "b");
}};
MapPropertySource mp1 = new MapPropertySource("mps", map1);
System.out.println(mp1.getName().equals("mps"));
  1. 有named方法和ComparisonPropertySource之后,就可以这样比较

System.out.println(mp1.equals(PropertySource.named("mps")));
  1. 好处是啥? 前者是字符串的比较,后者是对象的比较, 看他用在什么地方

PropertySource identity is determined not based on the content of encapsulated properties, but rather based on the name of the PropertySource alone. This is useful for manipulating PropertySource objects when in collection contexts. PropertySource的定位不是封装数据,而是对数据进行命名,以及方法在集合中操作.

  1. 如果是为了方便在集合中操作,那么就很有用了,如果你没有named方法,你必须要遍历List的数据,一个一个取出name值判断; 有了named方法后,现在你可以直接使用Collection中的方法来判断数据存不存在,删除数据等↓↓↓

List> propertySources = new ArrayList<>();
propertySources.contains(PropertySource.named("ps1"));
propertySources.remove(PropertySource.named("ps1"))

上述内容就是spring中 PropertySource类的作用是什么,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


网页标题:spring中PropertySource类的作用是什么
文章URL:http://cdxtjz.cn/article/gooseo.html

联系我们

您好HELLO!
感谢您来到成都网站建设公司,若您有合作意向,请您为我们留言或使用以下方式联系我们, 我们将尽快给你回复,并为您提供真诚的设计服务,谢谢。
  • 电话:028- 86922220 18980695689
  • 商务合作邮箱:631063699@qq.com
  • 合作QQ: 532337155
  • 成都网站设计地址:成都市青羊区锣锅巷31号五金站写字楼6楼

小谭建站工作室

成都小谭网站建设公司拥有多年以上互联网从业经验的团队,始终保持务实的风格,以"帮助客户成功"为已任,专注于提供对客户有价值的服务。 我们已为众企业及上市公司提供专业的网站建设服务。我们不只是一家网站建设的网络公司;我们对营销、技术、管理都有自己独特见解,小谭建站采取“创意+综合+营销”一体化的方式为您提供更专业的服务!

小谭观点

相对传统的成都网站建设公司而言,小谭是互联网中的网站品牌策划,我们精于企业品牌与互联网相结合的整体战略服务。
我们始终认为,网站必须注入企业基因,真正使网站成为企业vi的一部分,让整个网站品牌策划体系变的深入而持久。