1. PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。

2.在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码,如:

 <bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>conf/jdbc.properties</value>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>

3.PropertyPlaceholderConfigurer起的作用就是将占位符指向的数据库配置信息放在bean中定义的工具。

4.查看源代码,可以发现,locations属性定义在PropertyPlaceholderConfigurer的祖父类 PropertiesLoaderSupport中,而location只有 setter方法。类似于这样的配置,在spring的源程序中很常见的。

PropertyPlaceholderConfigurer如果在指定的Properties文件中找不到你想使用的属性,它还会在Java的System类属性中查找。

我们可以通过System.setProperty(key, value)或者java中通过-Dnamevalue来给Spring配置文件传递参数。

实例:

<bean class="com.slp.util.SpringContextHolder"/>
<bean id="propertyConfigurer"
class="com.slp.util.CustomizedPropertyConfigurer">
<property name="locations">
<list>
<value>classpath:conf/jdbc.properties</value> <value>classpath:conf/config.properties</value> <value>classpath:conf/server.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"/>
</bean>
package com.slp.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.util.HashMap;
import java.util.Map;
import java.util.Properties; public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer { private static Map<String,String> ctxPropMap; @Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
ctxPropMap = new HashMap<>();
for (Object key : props.keySet()){
String keyStr = key.toString();
String value = String.valueOf(props.get(keyStr));
ctxPropMap.put(keyStr,value);
}
} public static String getCtxProp(String name) {
return ctxPropMap.get(name);
} public static Map<String, String> getCtxPropMap() {
return ctxPropMap;
}
}
//使用的时候如下即可
CustomizedPropertyConfigurer.getCtxProp("xxx")

org.springframework.beans.factory.config

Class PropertyPlaceholderConfigurer

java.lang.Object-->

org.springframework.core.io.support.PropertiesLoaderSupport-->

org.springframework.beans.factory.config.PropertyResourceConfigurer-->

org.springframework.beans.factory.config.PlaceholderConfigurerSupport-->

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

以上即是PropertyPlaceholderConfigurer类的继承关系,

All Implemented Interfaces:所实现的接口

AwareBeanFactoryAwareBeanNameAwareBeanFactoryPostProcessorOrderedPriorityOrdered

Direct Known Subclasses:(直接的已知的子类)

PreferencesPlaceholderConfigurer

直接的子类:PreferencesPlaceholderConfigurer

public class PropertyPlaceholderConfigurer

extends PlaceholderConfigurerSupport

PlaceholderConfigurerSupport subclass that resolves ${...} placeholders against local properties and/or system properties and environment variables.

PlaceholderConfigurerSupport 的子类是用于解决${}的占位符,比如本地变量 或者系统变量或者环境变量等。

As of Spring 3.1, PropertySourcesPlaceholderConfigurer should be used preferentially over this implementation; it is more flexible through taking advantage of the Environment and PropertySource mechanisms also made available in Spring 3.1.

从spring3.1开始,propertysourcesplaceholderconfigurer应该在这些实现中优先使用,通过利用Environment 和PropertySource机制使得其更灵活。

PropertyPlaceholderConfigurer is still appropriate(合适的) for use when:

  • the spring-context module is not available (i.e., one is using Spring's BeanFactory API as opposed to ApplicationContext).
  • existing configuration makes use of the "systemPropertiesMode" and/or "systemPropertiesModeName" properties. Users are encouraged to move away from using these settings, and rather configure property source search order through the container's Environment; however, exact preservation of functionality may be maintained by continuing to use PropertyPlaceholderConfigurer.

Prior to Spring 3.1, the <context:property-placeholder/> namespace element registered an instance of PropertyPlaceholderConfigurer. It will still do so if using the spring-context-3.0.xsd definition of the namespace. That is, you can preserve registration of PropertyPlaceholderConfigurer through the namespace, even if using Spring 3.1; simply do not update your xsi:schemaLocation and continue using the 3.0 XSD.

在spring3.1之前<context:property-placeholder/> 命名空间注册了一个PropertyPlaceholderConfigurer的实例,如果你使用spring-context-3.0.xsd 之前依然是可以使用。

示例:例如一些配置文件中的常量为了简化不用频繁的更改参数配置信息,spring3.0中提供了一种简单的方式context:property-placeholder 元素。

只需要在spring的配置文件里添加一句:<context:property-placeholder location=””/>即可。这里的location值为参数配置文件的位置,参数配置文件与常用的参数配置文件相同,即键值对的形式。

PropertyPlaceholderConfiguration内置的功能非常丰富,如果未找到${xxx}中定义的xxx键,他还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找,通过启用systemPropertiesMode和searchSystemEnviroment属性,可以控制这一行为。

Since:

02.10.2003

Author:

Juergen Hoeller, Chris Beams

See Also:

setSystemPropertiesModeName(java.lang.String)PlaceholderConfigurerSupportPropertyOverrideConfigurerPropertySourcesPlaceholderConfigurer

Field Summary

Fields

Modifier and Type

Field and Description

static int

SYSTEM_PROPERTIES_MODE_FALLBACK

Check system properties if not resolvable in the specified properties.检查系统配置文件如果给定的配置文件没有该属性。

static int

SYSTEM_PROPERTIES_MODE_NEVER

Never check system properties.从不检查系统属性。

static int

SYSTEM_PROPERTIES_MODE_OVERRIDE

Check system properties first, before trying the specified properties.在检查特定的配置文件之前先检查系统配置文件。

Fields inherited from class org.springframework.beans.factory.config.PlaceholderConfigurerSupport

Fields inherited from class org.springframework.core.io.support.PropertiesLoaderSupport

Fields inherited from interface org.springframework.core.Ordered

Constructor Summary

Constructors

Constructor and Description

PropertyPlaceholderConfigurer()

Method Summary

All MethodsInstance MethodsConcrete Methods

Modifier and Type

Method and Description

protected void

processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)

Visit each bean definition in the given bean factory and attempt to replace ${...} property placeholders with values from the given properties.

访问bean工厂里面定义的所有bean并试图去使用给定的配置文件中的值去替换${}占位符。

protected String

resolvePlaceholder(String placeholder, Properties props)

Resolve the given placeholder using the given properties.使用给定的配置文件替换占位符。

protected String

resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode)

Resolve the given placeholder using the given properties, performing a system properties check according to the given mode.

protected String

resolveSystemProperty(String key)

Resolve the given key as JVM system property, and optionally also as system environment variable if no matching system property has been found.

void

setSearchSystemEnvironment(boolean searchSystemEnvironment)

Set whether to search for a matching system environment variable if no matching system property has been found.

void

setSystemPropertiesMode(int systemPropertiesMode)

Set how to check system properties: as fallback, as override, or never.

void

setSystemPropertiesModeName(String constantName)

Set the system property mode by the name of the corresponding constant, e.g.

Methods inherited from class org.springframework.beans.factory.config.PlaceholderConfigurerSupport

Methods inherited from class org.springframework.beans.factory.config.PropertyResourceConfigurer

Methods inherited from class org.springframework.core.io.support.PropertiesLoaderSupport

Methods inherited from class java.lang.Object

Field Detail

SYSTEM_PROPERTIES_MODE_NEVER

public static final int SYSTEM_PROPERTIES_MODE_NEVER

Never check system properties.

See Also:

Constant Field Values

SYSTEM_PROPERTIES_MODE_FALLBACK

public static final int SYSTEM_PROPERTIES_MODE_FALLBACK

Check system properties if not resolvable in the specified properties. This is the default.

See Also:

Constant Field Values

SYSTEM_PROPERTIES_MODE_OVERRIDE

public static final int SYSTEM_PROPERTIES_MODE_OVERRIDE

Check system properties first, before trying the specified properties. This allows system properties to override any other property source.

See Also:

Constant Field Values

Constructor Detail

PropertyPlaceholderConfigurer

public PropertyPlaceholderConfigurer()

Method Detail

setSystemPropertiesModeName

public void setSystemPropertiesModeName(String constantName)

throws IllegalArgumentException

Set the system property mode by the name of the corresponding constant, e.g. "SYSTEM_PROPERTIES_MODE_OVERRIDE".

Parameters:

constantName - name of the constant

Throws:

IllegalArgumentException - if an invalid constant was specified

See Also:

setSystemPropertiesMode(int)

setSystemPropertiesMode

public void setSystemPropertiesMode(int systemPropertiesMode)

Set how to check system properties: as fallback, as override, or never. For example, will resolve ${user.dir} to the "user.dir" system property.

The default is "fallback": If not being able to resolve a placeholder with the specified properties, a system property will be tried. "override" will check for a system property first, before trying the specified properties. "never" will not check system properties at all.

See Also:

SYSTEM_PROPERTIES_MODE_NEVERSYSTEM_PROPERTIES_MODE_FALLBACKSYSTEM_PROPERTIES_MODE_OVERRIDEsetSystemPropertiesModeName(java.lang.String)

setSearchSystemEnvironment

public void setSearchSystemEnvironment(boolean searchSystemEnvironment)

Set whether to search for a matching system environment variable if no matching system property has been found. Only applied when "systemPropertyMode" is active (i.e. "fallback" or "override"), right after checking JVM system properties.

Default is "true". Switch this setting off to never resolve placeholders against system environment variables. Note that it is generally recommended to pass external values in as JVM system properties: This can easily be achieved in a startup script, even for existing environment variables.

NOTE: Access to environment variables does not work on the Sun VM 1.4, where the corresponding System.getenv(java.lang.String) support was disabled - before it eventually got re-enabled for the Sun VM 1.5. Please upgrade to 1.5 (or higher) if you intend to rely on the environment variable support.

See Also:

setSystemPropertiesMode(int)System.getProperty(String)System.getenv(String)

resolvePlaceholder

protected String resolvePlaceholder(String placeholder,Properties props,int systemPropertiesMode)

Resolve the given placeholder using the given properties, performing a system properties check according to the given mode.

The default implementation delegates to resolvePlaceholder (placeholder, props) before/after the system properties check.

Subclasses can override this for custom resolution strategies, including customized points for the system properties check.

Parameters:

placeholder - the placeholder to resolve

props - the merged properties of this configurer

systemPropertiesMode - the system properties mode, according to the constants in this class

Returns:

the resolved value, of null if none

See Also:

setSystemPropertiesMode(int)System.getProperty(java.lang.String)resolvePlaceholder(String, java.util.Properties)

resolvePlaceholder

protected String resolvePlaceholder(String placeholder, Properties props)

Resolve the given placeholder using the given properties. The default implementation simply checks for a corresponding property key.

Subclasses can override this for customized placeholder-to-key mappings or custom resolution strategies, possibly just using the given properties as fallback.

Note that system properties will still be checked before respectively after this method is invoked, according to the system properties mode.

Parameters:

placeholder - the placeholder to resolve

props - the merged properties of this configurer

Returns:

the resolved value, of null if none

See Also:

setSystemPropertiesMode(int)

resolveSystemProperty

protected String resolveSystemProperty(String key)

Resolve the given key as JVM system property, and optionally also as system environment variable if no matching system property has been found.

Parameters:

key - the placeholder to resolve as system property key

Returns:

the system property value, or null if not found

See Also:

setSearchSystemEnvironment(boolean)System.getProperty(String)System.getenv(String)

processProperties

protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props)throws BeansException

Visit each bean definition in the given bean factory and attempt to replace ${...} property placeholders with values from the given properties.

Specified by:

processProperties in class PropertyResourceConfigurer

Parameters:

beanFactoryToProcess - the BeanFactory used by the application context

props - the Properties to apply

Throws:

BeansException - in case of errors

PropertyPlaceholderConfigurer读取配置文件的更多相关文章

  1. spring读取配置文件PropertyPlaceholderConfigurer类的使用

    这里主要介绍PropertyPlaceholderConfigurer这个类的使用,spring中的该类主要用来读取配置文件并将配置文件中的变量设置到上下文环境中,并进行赋值. 一.此处使用list标 ...

  2. java web路径和spring读取配置文件

    此篇博客缘起:部署java web系统到阿里云服务器(ubuntu14.04)的时候,有以下两个问题 找不到自定义的property配置文件 上传图片的时候找不到路径 开发的时候是在windows上的 ...

  3. java读取配置文件方法以及工具类

    第一种方式 : java工具类读取配置文件工具类 只是案例代码  抓取异常以后的代码自己处理 import java.io.FileNotFoundException; import java.io. ...

  4. Spring读取配置文件 @Value

    最近在学习Spring如何读取配置文件,记录下方便自己也方便别人: 大致分为两类吧,一种的思路是利用Spring的beanFactoryPostProcessor读取配置文件内容到内存中,也就是应用程 ...

  5. Spring 读取配置文件(二)

    Spring 读取配置文件并调用 bean package cn.com.test.receive; import org.springframework.beans.factory.annotati ...

  6. Spring 读取配置文件(一)

    注册 @Configuration 标识的类,spring 读取配置文件的时候该类会被自动装载 package cn.com.receive;import org.springframework.be ...

  7. java properties类读取配置文件

    1.JAVA Properties类,在java.util包里,具体类是java.util.properties.Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值 ...

  8. 关于spring读取配置文件的两种方式

    很多时候我们把需要随时调整的参数需要放在配置文件中单独进行读取,这就是软编码,相对于硬编码,软编码可以避免频繁修改类文件,频繁编译,必要时只需要用文本编辑器打开配置文件更改参数就行.但没有使用框架之前 ...

  9. 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 我们在 读取配置文件(一) appsettings.json 中介绍了,如何读取appsettings.json. 但随之产生 ...

随机推荐

  1. Liunx 安装 Mysql 5.7

    #[安装 Mysql 5.7] # 00.系统目录说明# 安装文件下载目录:/data/software# Mysql目录安装位置:/usr/local/mysql# 数据库保存位置:/data/my ...

  2. java资料——哈希表(散列表)(转)

    哈希表       散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构.也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度. ...

  3. log4j日志pattern配置

    c category的名称,可使用{n}限制输出的精度.例如:logger名为"a.b.c",%c{2}将输出"b.c". C 产生log事件的java完全限定 ...

  4. awk多列匹配

    1.1.1 awk多列匹配 [hadoop@st1 data]$ netstat -an|awk  '$1~/tcp/&&$3~/64/{print $0}' tcp        0 ...

  5. C++中 char *s 和 char s[] 的区别

    原因 刚好看到给main传递参数,书上(C++Primer)说“ int main(int argc, char *argv[])也可以写成 int main(int argc, char **arg ...

  6. 第三百一十八节,Django框架,信号

    第三百一十八节,Django框架,信号 Django中提供了“信号调度”,用于在框架执行操作时解耦.通俗来讲,就是一些动作发生的时候,信号允许特定的发送者去提醒一些接受者. 也就是当程序有指定动作时, ...

  7. e666. 创建缓冲图像

    A buffered image is a type of image whose pixels can be modified. For example, you can draw on a buf ...

  8. nodejs基础 -- 回调函数

    Node.js 异步编程的直接体现就是回调. 异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了. 回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都 ...

  9. CentOS 7 Minimal编译安装MySQL5.6

    写在前面,编译安装MySQL的优势:平台无关.可设定参数按需安装.安装的MySQL目录独立(方便清楚).更好的平台耦合及运行性能(很多运维的观点):缺点:编译安装较慢. 一.撤换系统防火墙 注:Cen ...

  10. C/C++,从未过时的编程语言之父

    C/C++,持续火爆的编程语言之父 --訪传智播客C/C++学院院长传智·萧峰 编程语言作为实现互联网+基础必备工具,构建着互联网行业美轮美奂的大时代.作为编程语言之父--C语言,更是如鱼得水,在甘愿 ...