订制网站建设,在wordpress 需要购买服务器吗,wordpress 4 安装教程,山东电力建设河北分公司网站在spring中#xff0c;如果要给程序定义一些参数#xff0c;可以放在application.properties中#xff0c;通过context:property-placeholder加载这个属性文件#xff0c;然后就可以通过value给我们的变量自动赋值#xff0c;如果你们的程序可能运行在多个环境中如果要给程序定义一些参数可以放在application.properties中通过context:property-placeholder加载这个属性文件然后就可以通过value给我们的变量自动赋值如果你们的程序可能运行在多个环境中比如开发、测试和生产你也可以定义多套属性文件。这些用法我们早已司空见惯今天我们就来理一下来龙去脉。
context:property-placeholder
用法
context:property-placeholder的主要属性
属性名 说明location文件位置多个之间通过如逗号/分号等分隔file-encoding文件编码ignore-resource-not-found如果属性文件找不到是否忽略默认false即不忽略找不到将抛出异常 ignore-unresolvable是否忽略解析不到的属性如果不忽略找不到将抛出异常properties-ref本地java.util.Properties配置local-override是否本地覆盖模式即如果true本地属性文件的优先级高于环境变量system-properties-mode 系统属性模式 ENVIRONMENT默认 FALLBACK(环境变量兜底 NEVER不使用环境变量 OVERRIDE环境变量覆盖
历史渊源
要说清楚这个标签涉及spring3.1这个重要版本从这个版本起spring抽象了Environment接口这个标签的处理器也从PropertyPlaceholderConfigurer被过渡到PropertySourcesPlaceholderConfigurer下面细讲。
关于system-properties-mode属性
在3.1之前只有三个取值当时的处理器还是PropertyPlaceholderConfigurer这个处理现在已经不推荐使用这个变量的作用是声明对系统属性和环境变量的使用方式。
属性值说明NEVER不使用系统属性和环境变量OVERRIDE 使用系统属性和环境变量覆盖属性文件 即系统属性和环境变量优先 FALLBACK 使用系统属性和环境变量来做兜底 即属性文件优先
在3.1之后多了一个新的取值Environmentspring从这个版本起引入了Environment接口如果system-properties-mode属性被配置为Environment则使用采用PropertySourcesPlaceholderConfigurer进行占位符处理这也是3.1之后的默认处理方式。
见PropertyPlaceholderBeanDefinitionParser: Overrideprotected Class? getBeanClass(Element element) {//system-properties-mode设置为ENVIRONMENT则走PropertySourcesPlaceholderConfigurerif (SYSTEM_PROPERTIES_MODE_DEFAULT.equals(element.getAttribute(SYSTEM_PROPERTIES_MODE_ATTRIBUTE))) {return PropertySourcesPlaceholderConfigurer.class;}//否则走PropertyPlaceholderConfigurer兼容处理return PropertyPlaceholderConfigurer.class;} 各种配置的优化级
由于system-properties-mode只推荐使用ENVIRONMENT其它三种方式只是保持对老版本spring的兼容这里主要分析在ENVIRONMENT模式下属性文件properties-ref系统属性环境变量的优先级
local-override属性值优先级false System.getProperty()System.getenv() location属性文件properties-ref trueproperties-reflocation属性文件System.getProperty()System.getenv()
默认情况下系统属性和环境变量一起构成StandardEnvironment系统属性优先于环境变量。
public class StandardEnvironment extends AbstractEnvironment {/** System environment property source name: {value}. */public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME systemEnvironment;/** JVM system properties property source name: {value}. */public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME systemProperties;//加入定义两个PropertySource:这个是系统属性一个是环境变量Overrideprotected void customizePropertySources(MutablePropertySources propertySources) {propertySources.addLast(new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));}} PropertySourcesPlaceholderConfigurer
PropertySourcesPlaceholderConfigurer维护一个MutablePropertySources该对象放着两个PropertySource一个对Environment做了一个包装一个是合并本地的属性文件配置。并local-override的配置的不同决定这两个PropertySource的优先级
#postProcessBeanFatcory
作为一个BeanFactoryPostProcessor该方法会在Bean实例化之前被spring容器调用
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {if (this.propertySources null) {this.propertySources new MutablePropertySources();if (this.environment ! null) {this.propertySources.addLast(//将Environment封装成一个新的PropertySource后面的占位符处理将委托给Environment对象new PropertySourceEnvironment(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {OverrideNullablepublic String getProperty(String key) {return this.source.getProperty(key);}});}try {//合并properties-ref和location的属性合并并统称为localPropertiesPropertySource? localPropertySource new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());if (this.localOverride) {//如果本地覆盖则将本地属性放在首位(优先)this.propertySources.addFirst(localPropertySource);}else {//否则将本地属性放在未位this.propertySources.addLast(localPropertySource);}}catch (IOException ex) {throw new BeanInitializationException(Could not load properties, ex);}}//处理属性占位符这里只是将占位符处理器注入给到BeanFactoryprocessProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));this.appliedPropertySources this.propertySources;}
#mergeProperties
mergeProperties方法合并location指向的属性文件和properties-ref指向的配置对象。如果全地覆盖则使用properties-ref覆盖location的配置否则相反。其中loadProperties是加载location指定的属性文件并解析代析Properties对象代码略
protected Properties mergeProperties() throws IOException {Properties result new Properties();if (this.localOverride) {// 如果本地覆盖则先加载location指定的属性文件loadProperties(result);}if (this.localProperties ! null) {//如果定义了properties-ref属性则进行属性合并for (Properties localProp : this.localProperties) {CollectionUtils.mergePropertiesIntoMap(localProp, result);}}if (!this.localOverride) {//如果非本地覆盖则最后加载location指定的属性文件loadProperties(result);}return result;}
#processProperties
进入processProperties方法ConfigurablePropertyResolver 最终被转换成StringValueResolver然后调用doProcessProperties。
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,final ConfigurablePropertyResolver propertyResolver) throws BeansException {propertyResolver.setPlaceholderPrefix(this.placeholderPrefix);propertyResolver.setPlaceholderSuffix(this.placeholderSuffix);propertyResolver.setValueSeparator(this.valueSeparator);StringValueResolver valueResolver strVal - {String resolved (this.ignoreUnresolvablePlaceholders ?propertyResolver.resolvePlaceholders(strVal) :propertyResolver.resolveRequiredPlaceholders(strVal));if (this.trimValues) {resolved resolved.trim();}return (resolved.equals(this.nullValue) ? null : resolved);};doProcessProperties(beanFactoryToProcess, valueResolver);}
#doProcessProperties
进入doProcessProperties该方法进行处理BeanDefinition中的各种占位符最后把StringValueResolver注入给beanFactory供属性代替使用后面会讲到。
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,StringValueResolver valueResolver) {BeanDefinitionVisitor visitor new BeanDefinitionVisitor(valueResolver);String[] beanNames beanFactoryToProcess.getBeanDefinitionNames();for (String curName : beanNames) {if (!(curName.equals(this.beanName) beanFactoryToProcess.equals(this.beanFactory))) {BeanDefinition bd beanFactoryToProcess.getBeanDefinition(curName);try {//处理BeanDefinition中的各种占位符注意不是bean本身)visitor.visitBeanDefinition(bd);}catch (Exception ex) {throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage(), ex);}}}beanFactoryToProcess.resolveAliases(valueResolver);//在这里把StringValueResolver注入给beanFactory供属性代替使用beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);}
相关接口说明
PropertyResolver接口
在PropertySourcesPlaceholderConfigurer中会创建PropertyResolver接口对象该对象持有配置属性源的引用并提供获取属性值处理占位符等功能。详见PropertySourcesPropertyResolver这里只列出接口的定义
public interface PropertyResolver {boolean containsProperty(String key);NullableString getProperty(String key);//获取属性值String getProperty(String key, String defaultValue);NullableT T getProperty(String key, ClassT targetType);T T getProperty(String key, ClassT targetType, T defaultValue);String getRequiredProperty(String key) throws IllegalStateException;T T getRequiredProperty(String key, ClassT targetType) throws IllegalStateException;String resolvePlaceholders(String text);//处理占位符String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
}
Environment
Environment接口是Spring体系里一个既熟悉又陌生的接口。
Spring 3.1 开始引入 Environment 抽象它统一 Spring 配置属性的存储、占位符处理和类型转换支持更丰富的配置属性源PropertySource。
条件化 Spring Bean 装配管理 通过 Environment Profiles 信息帮助 Spring 容器提供条件化地装配 Bean。
Profile
在spring应用中通常会通过变量spring.profiles.active去指定当前环境而注解Profile可以加上Bean上让Bean在某个环境中生效其实现通过Conditional(ProfileCondition.class)这里不展开。
Environment接口继承自PropertyResolver同时扩展了对profile的操作通过profile来标识当前处于哪个环境开发、测试或生产
public interface Environment extends PropertyResolver {//获取当前profile(环境)String[] getActiveProfiles();String[] getDefaultProfiles();Deprecatedboolean acceptsProfiles(String... profiles);//判断当前环境是否与给定profiles一致boolean acceptsProfiles(Profiles profiles);
}
AbstractEnvironment
结合抽象类AbstractEnvironment可以更好地理解Environment的行为
public abstract class AbstractEnvironment implements ConfigurableEnvironment {//维护当前活动的profile环境private final SetString activeProfiles new LinkedHashSet();private final SetString defaultProfiles new LinkedHashSet(getReservedDefaultProfiles());//维护各种配置属性源private final MutablePropertySources propertySources new MutablePropertySources();//持有占位符处理器private final ConfigurablePropertyResolver propertyResolver new PropertySourcesPropertyResolver(this.propertySources);
} AbstractEnvironment由于知道当前是哪个环境就知道需要装载哪些配置文件,而MutablePropertySources是可变的PropertySources,它允许用户动态地添加各种PropertySource,比如来自配置中心的配置。最后由propertyResolver完成最后的占位符处理操作。
PropertySource
属性源就是对一类配置(可以是属性配置文件系统属性环境变量等的封装同时给这个配置一个名称
public abstract class PropertySourceT {protected final String name;//名称protected final T source;//配置存放键值对...}
MapPropertySource一种基于Map实现的简单的PropertySource。
public class MapPropertySource extends EnumerablePropertySourceMapString, Object {public MapPropertySource(String name, MapString, Object source) {super(name, source);}OverrideNullablepublic Object getProperty(String name) {return this.source.get(name);}Overridepublic boolean containsProperty(String name) {return this.source.containsKey(name);}Overridepublic String[] getPropertyNames() {return StringUtils.toStringArray(this.source.keySet());}}
只要你喜欢你可以把Map当做你的配置源也就是说你可以把创建一个Map作为应用程序的配置。一些主要的PropertySource.
PropertySource 类型说明org.springframework.core.env.CommandLinePropertySource命令行配置属性源org.springframework.jndi.JndiPropertySourceJDNI 配置属性源org.springframework.core.env.MapPropertySource基于Map对象的配置属性源org.springframework.core.env.PropertiesPropertySource 扩展自MapPropertySource Properties 配置属性源 org.springframework.web.context.support.ServletConfigPropertySourceServlet 配置属性源org.springframework.web.context.support.ServletContextPropertySourceServletContext 配置属性源org.springframework.core.env.SystemEnvironmentPropertySource环境变量配置属性源
其中PropertiesPropertySource扩展自MapPropertySource,我们的系统属性以及我们属性配置文件最终会被封装成PropertiesPropertySource其它配置属性源请自行脑补。
PropertySources
PropertySources是PropertySource的集合是一个继承自Iterable的接口提供了一些方便操作属性源的方法
addFirst()将属性源放在首位即优先级最高addLast()将属性源放在未位即优先级最低
MutablePropertySources
PropertySources有一个唯一的实现MutablePropertySources。该实现就是Environment对象里的可变属性源基于该对象可以实现PropertySource的动态地添加并按需对属性源进行优先级排序。
注在spring中有对应的注解如PropertySource和PropertySources可以以注解的形成来配置属性源随着applicationContext.xml慢慢被摈弃正逐渐代替context:property-placeholder,这里不展开。
如何动态添加属性源
通过调用ConfigurableApplicationContext#getEnvironment可以获得到Environment引用再把自己扩展的PropertySource添加到它的MutablePropertySources里面。
ConfigurableEnvironment environment context.getEnvironment();
MapPropertySource mapPropertySource new MapPropertySource(my-map-properties, new HashMap());
MutablePropertySources propertySources environment.getPropertySources();
propertySources.addFirst(mapPropertySource);
Value的实现
上面讲了Enviroment抽象以及属性源优先级下面讲Value注释如何实现属性值的替换。
AutowiredAnnotationBeanPostProcessor
多数人对Value这一块并不陌生主要的实现就是AutowiredAnnotationBeanPostProcessor该BeanPostProcessor主要处理Value和Autowired注解。这里就不贴代码了大概流程如下 spring容器在创建完Bean对象实现实例之后进入属性注入阶段会回postProcessPropertyValues方法BeanPostProcessor的回调机制进而会调用beanFactory.resolveDependencyAutowiredAnnotationBeanPostProcessor实现了BeanFactoryAware接口持有beanFactory对象引用
DefaultListableBeanFactory#doResolveDependency
Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, Nullable String beanName,Nullable SetString autowiredBeanNames, Nullable TypeConverter typeConverter) throws BeansException {InjectionPoint previousInjectionPoint ConstructorResolver.setCurrentInjectionPoint(descriptor);try {Object shortcut descriptor.resolveShortcut(this);if (shortcut ! null) {return shortcut;}Class? type descriptor.getDependencyType();Object value getAutowireCandidateResolver().getSuggestedValue(descriptor);if (value ! null) {if (value instanceof String) {//这里处理属性值String strVal resolveEmbeddedValue((String) value);BeanDefinition bd (beanName ! null containsBean(beanName) ?getMergedBeanDefinition(beanName) : null);value evaluateBeanDefinitionString(strVal, bd);}//对属性值做类型转换TypeConverter converter (typeConverter ! null ? typeConverter : getTypeConverter());try {return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());}catch (UnsupportedOperationException ex) {// A custom TypeConverter which does not support TypeDescriptor resolution...return (descriptor.getField() ! null ?converter.convertIfNecessary(value, type, descriptor.getField()) :converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));}}
...
}2beanFactory.resolveDependency的主要作用是处理属性依赖可以处理对象的注入也可以处理属性值的注入。如果是Value属性值注入则进行占位符处理而在BeanFactory里处理占位符的对象是StringValueResolverBeanFactory维护多个StringValueResolver
public String resolveEmbeddedValue(Nullable String value) {if (value null) {return null;}String result value;//这里的StringValueResolver有一个是PropertySourcesPlaceholderConfigurer注入的for (StringValueResolver resolver : this.embeddedValueResolvers) {result resolver.resolveStringValue(result);if (result null) {return null;}}return result;}
BeanFactory对属性值的处理就是交给多个StringValueResolver去循环处理这里的StringValueResolver有一个是PropertySourcesPlaceholderConfigurer注入的可回头看PlaceholderConfigurerSupport#doProcessProperties。
StringValueResolver接口
回到StringValueResolver接口该接口只做一件事那就是做占位符处理将一个字符串转成另一个字符串
FunctionalInterface
public interface StringValueResolver {NullableString resolveStringValue(String strVal);}
那问题来了为何BeanFactory不直接持有PropertyResolver对象而要使用新的接口呢
这里要说明的是PropertyResolver接口是spring3.1才引入的而StringValueResolver则在spring2.5就已经存在一方面BeanFactory原先持有的就是StringValueResolver另一个方面这突显了接口设计的单一原则因为对于BeanFactory而言就仅仅是想得到目标的属性值。因而也就没有必要换成PropertyResolver接口。
总结
回顾context:property-placeholder和Value的整个过程
1自spring3.1起采用PropertySourcesPlaceholderConfigurer维护一个聚合了Environment环境变量和系统属性和本地属性文件的配置将Environment包装成一个新的PropertySource中。
2PropertySourcesPlaceholderConfigurer维护一个MutablePropertySources该对象放着两个PropertySource一个对Environment做了一个包装一个是合并本地的属性文件配置。并local-override的配置的不同决定这两个PropertySource的优先级
3PropertySourcesPlaceholderConfigurer创建了PropertyResolver接口对象并适配成StringValueResolver接口传递给BeanFactory由于PropertyResolver对象持有MutablePropertySources引用因此这个MutablePropertySources对BeanFactory可见。
4BeanFactory维护着一系列StringValueResolver对象并提供处理对象依赖包括属性值的能力。
5属性值注入阶段AutowiredAnnotationBeanPostProcessor通过调用BeanFactory的doResolveDependency实现属性注入内部调用StringValueResolver进行属性值处理而本质上就是调用PropertySourcesPlaceholderConfigurer的PropertyResolver最终使用的也是PropertySourcesPlaceholderConfigurer中的的MutablePropertySources。
6得益于Environment的MutablePropertySources应用可以更灵活地管理各种配置及其优先级。
最后献上一个类图 by simple