Spring-全量自定义-PropertySource

Spring的PropertySource接口用于处理属性资源,常与属性解析器配合,提供name/value形式的存储。它可以被自定义以适应不同场景,如ServletContext,甚至从网络位置获取资源。MapPropertySource是常见实现,而EnumerablePropertySource允许枚举属性名,方便业务需求定制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PropertySource:属性资源,以name/value形式存储

protected final String name; //属性名字
protected final T source; //属性资源

配合属性解析器使用的接口:

public boolean containsProperty(String name) {//判断该资源是否含有指定名称的key
		return (getProperty(name) != null);
	}
@Nullable
public abstract Object getProperty(String name);//从资源中获取值

占位资源,用于保证自己的顺序,后续通过replace换成真实资源,例如ServeltContext等:

public static class StubPropertySource extends PropertySource<Object> {
		public StubPropertySource(String name) {
			super(name, new Object());
		}
		@Override
		@Nullable
		public String getProperty(String name) {
			return null;
		}
	}

在springframework核心包中有一个实现,可以枚举属性名字:

public abstract class EnumerablePropertySource<T> extends PropertySource<T> {

	public EnumerablePropertySource(String name, T source) {
		super(name, source);
	}
	protected EnumerablePropertySource(String name) {
		super(name);
	}
	@Override
	public boolean containsProperty(String name) {
		return ObjectUtils.containsElement(getPropertyNames(), name);
	}
	//枚举所有属性名字
	public abstract String[] getPropertyNames();

}

EnumerablePropertySource的直接实现:

CompositePropertySource (org.springframework.core.env)//符合型实现,有一个set持有PropertySource
CommandLinePropertySource (org.springframework.core.env)//命令行属性资源
MapPropertySource (org.springframework.core.env)//map型资源
AnnotationsPropertySource (org.springframework.boot.test.autoconfigure.properties)//通过注解注入的属性资源

其中MapPropertySource是使用较广的,他的实现有:

PropertiesPropertySource (org.springframework.core.env)//通过Properties资源构建属性资源
       ResourcePropertySource (org.springframework.core.io.support)//直接通过资源路径构建属性资源
       MockPropertySource (org.springframework.mock.env)//测试使用的属性资源
SystemEnvironmentPropertySource (org.springframework.core.env)//对系统环境转换成属性资源

命令行属性资源:

CommandLinePropertySource (org.springframework.core.env)
		SimpleCommandLinePropertySource (org.springframework.core.env)//能够吧命令行参数封装成属性资源

通过上面的源码解析,可以看到,spring的属性资源,按照不同的场景,可以自行构建自定义属性资源,从而能解析符合自己业务需求的资源,比如从某个网络位置进行资源解析,等等.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值