美文网首页
Spring Properties使用的几种方式

Spring Properties使用的几种方式

作者: 银河舰长 | 来源:发表于2019-06-06 11:16 被阅读0次

1.PropertyPlaceholderConfigurer类

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

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

相关文章

网友评论

      本文标题:Spring Properties使用的几种方式

      本文链接:https://www.haomeiwen.com/subject/tdxexctx.html