PropertyOverrideConfigurer和PropertyPlaceholderConfigurer有什么区别?

Sid*_*rth 4 java xml spring javabeans

使用PropertyOverrideConfigurerPropertyPlaceholderConfigurer在Spring框架之间有什么区别?我无法在这两个类之间找到任何明显的区别.

kuh*_*yan 8

PropertyOverrideConfigurer:

"属性资源配置器,它覆盖应用程序上下文定义中的bean属性值.它将属性文件中的值推送到bean定义中."

它允许您覆盖bean所采用的某些值,这意味着您可以从属性文件中定义的属性覆盖一些spring bean的值

宣布:

<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
    <property name="location" value="classpath:myproperties.properties" />
</bean>

<bean id="person" class="com.sample.Employee" >
       <property name="name" value="Dugan"/>
       <property name="age" value="50"/>       
</bean> 
Run Code Online (Sandbox Code Playgroud)

myproperties.properties:

person.age=40
person.name=Stanis
Run Code Online (Sandbox Code Playgroud)

所以加载bean时

Employee e  = (Employee)context.getBean(Employee.class);

e.getAge() => 40
e.getName() => "Stanis"
Run Code Online (Sandbox Code Playgroud)

PropertyPlaceholderConfigurer:

针对本地属性和/或系统属性和环境变量解析$ {...}占位符.

它允许您在bean定义中解析$ {..}占位符,它还会检查值的系统属性.可以使用systemPropertiesMode控制此行为

  • never(0):从不检查系统属性
  • fallback(1):如果在指定的属性文件中无法解析,则检查系统属性.这是默认值.
  • override(2):在尝试指定的属性文件之前,首先检查系统属性.这允许系统属性覆盖任何其他属性源.

配置

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
        <property name="username" value="root" />
        <property name="password" value="password" />
        <property name="systemPropertiesMode" value="0" />
    </bean>
Run Code Online (Sandbox Code Playgroud)

将'dataSource'属性移动到属性文件

database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=root
jdbc.password=password



<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="location">
        <value>database.properties</value>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

然后用占位符引用它们=>

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
Run Code Online (Sandbox Code Playgroud)