【问题标题】:How can I set Spring property from the XML configuration file?如何从 XML 配置文件中设置 Spring 属性?
【发布时间】:2017-02-15 06:06:32
【问题描述】:

我有一些使用属性的 spring 配置,如下所示:

<bean id="foo" class="...">
    <constructor-arg value="${aProperty}"/>
</bean>

显然我知道我可以通过拥有一个属性文件(例如 example.properties)来解决此属性:

aProperty=value

并在 Spring 配置中导入此文件:

<bean id="propertyConfiguration" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>example.properties</value>
        </list>
    </property>
</bean>

我的问题是,我可以直接在 XML 文件中设置此属性,而不必创建单独的属性文件吗?像这样的东西是理想的:

<set-property name="aProperty" value="value"/>

Maven 对 pom 文件有类似的功能:

<properties><aProperty>value</aProperty></properies>

【问题讨论】:

    标签: xml spring configuration


    【解决方案1】:

    使用属性文件的目的是将值与 Spring 配置文件分离,因此在同一个配置文件中定义属性有点奇怪。尽管如此,您始终可以向您的 PropertyPlaceholderConfigurer 添加属性:

    <bean id="propertyConfiguration" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>example.properties</value>
            </list>
        </property>
        <property name="properties">
            <props>
                <prop key="aa">bb</prop>
                <prop key="cc">dd</prop>
            </props>
        </property>
    </bean>
    

    希望对你有帮助。

    【讨论】:

    • 完美。想要这样做的原因是属性值本身是传递给第三方库的属性文件的名称。因为这是我的应用程序的 6 个以上实例之间唯一不同的属性,所以我不想创建六个新的属性文件,所有这些文件都有一个属性,它是另一个属性文件的名称!
    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2011-03-21
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多