Use Java util properties instead of propertyplaceh

2019-08-14 03:21发布

问题:

I need to dynamically placehold the property values in springbeans.xml using Java.util.properties instead of PropertyPlaceHolderConfigurator in Spring Eg.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location" value="file:test.properties" />
 </bean>   
<bean id="dbconnectionFactory" class="com.test.Test">           
      <property name="username" value="${username}" />
      <property name="password" value="${password}" />
 </bean>

Can I use java.util.properties to mimic the same result i.e.

<bean id="javaproperty" class="java.util.Properties">
                                   <property name="location" value="file:test.properties" />
            </bean> 

            <bean id="dbconnectionFactory"
                        class="con.test.Test">

              <property name="username" value="${username}" />
                        <property name="password" value="${password}" />
            </bean>

回答1:

As you are already using Spring, you could do

<bean id="properties"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath*:application.properties</value>
        </list>
    </property>
</bean

And then just inject it, it is of type java.util.properties

@Resource
private Properties properties;