Spring基础:Properties使用方式最全面的总结

1,989 阅读2分钟

1.PropertyPlaceholderConfigurer类

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

  • 使用PropertyPlaceholderConfigurer方式加载的配置键值,可以在xml文件中通过${***}占位符引入,也可以在类(class)中通过@Value("${***}")注解在变量上注入值。
<!-- 在xml中的使用方式 -->
<property name="***" value="${***}"/>
/** 在java类中的使用方式 **/
@Value("${***}")
private String ***;
  • locations参数 支持String[]类型,可以同时传入多个配置文件的地址(支持*通配符填入地址)。

特别提示:
在<value>***</value>标签中的地址,不限于本地路径。使用URL格式填入资源文件地址即可,如: http://x.y.z/abc.properties URL格式的地址会被Spring解析为org.springframework.core.io.Resource类型的资源引用,目前Resource支持的类型有WritableResource、ContextResource、UrlResource、FileUrlResource、FileSystemResource、 ClassPathResource、ByteArrayResource、InputStreamResource八种。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:resource1.properties</value>
            <value>classpath:config/resource2.properties</value>
            <value>classpath*:resource3.properties</value>
        </list>
    </property>
</bean>

2. context:property-placeholder标签

<context:property-placeholder location="classpath:***"/>

  • 使用方法同PropertyPlaceholderConfigurer类的方式相同,可以在xml文件中通${***}占位符引入,也可以在类(class)中通过@Value("${***}")注解在变量上注入值。
  • 需要在beans配置文件中,声明context命名空间。
<beans xmlns:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
  • 使用context提供的proerty-placeholder标签加载配置文件,在location参数填入需要加载文件的路径,多个文件使用逗号分隔(注意:多个文件都需要填写各自的完整路径)。
<context:property-placeholder location="classpath*:config/*.properties,classpath*:other.properties"/>
  • 如果在beans配置文件中多次定义并加载该标签,则只有最先被加载的标签生效。
  • 如果在该标签的location参数中引入的文件有重复的键值,则靠后(更右侧会更晚加载)的资源文件中的键值,会覆盖靠前的已加载的键值。

3.PropertiesFactoryBean类

org.springframework.beans.factory.config.PropertiesFactoryBean

  • 使用#{BeanID['***']}的方式注入键值,不能使用PropertiesFactoryBean类注入键值的方法(即${***}格式不能注入PropertiesFactoryBean加载的键值)。
<!-- id是必须声明的,注入键值时需要使用 -->
<bean id="proertiesHolder" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:resource1.properties</value>
            <value>classpath:config/resource2.properties</value>
            <value>classpath*:resource3.properties</value>
        </list>
    </property>
</bean>
<!-- 在xml中的使用方式 -->
<property name="***" value="#{proertiesHolder['***']}"/>
/** 在java类中的使用方式 **/
@Value("#{proertiesHolder['***']}")
private String ***;