本文共 1923 字,大约阅读时间需要 6 分钟。
PropertySource:属性资源,以name/value形式存储
protected final String name; //属性名字protected final T source; //属性资源
配合属性解析器使用的接口:
public boolean containsProperty(String name) {//判断该资源是否含有指定名称的key return (getProperty(name) != null); }@Nullablepublic abstract Object getProperty(String name);//从资源中获取值
占位资源,用于保证自己的顺序,后续通过replace换成真实资源,例如ServeltContext等:
public static class StubPropertySource extends PropertySource
在springframework核心包中有一个实现,可以枚举属性名字:
public abstract class EnumerablePropertySourceextends PropertySource { 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持有PropertySourceCommandLinePropertySource (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的属性资源,按照不同的场景,可以自行构建自定义属性资源,从而能解析符合自己业务需求的资源,比如从某个网络位置进行资源解析,等等.
转载地址:http://wduti.baihongyu.com/