【问题标题】:Store Custom properties in aplicationContext.xml Spring file将自定义属性存储在 applicationContext.xml Spring 文件中
【发布时间】:2010-10-27 16:32:20
【问题描述】:

我需要为使用 spring 框架的 web 应用程序存储一些配置参数。

通常我会使用 configurationfile.properties 文件,但我想知道是否可以将这些值存储在 applicationContext.xml 文件中。

一种解决方法是创建一个 JavaBean 类来存储值,并使用 spring 构建该类,如下所示:

<bean id="configurationBean" class="mypackage.someClass">
 <property name="confValue1">
   <value>myValue1</value>
 </property>
 ....
</bean>

但我想知道是否有一种方法可以存储这些参数而无需创建该类。

提前致谢。


我认为符合我要求的最佳解决方案是使用 java.util.Properties 实例作为 Spring Bean。

谢谢大家。

【问题讨论】:

    标签: spring properties


    【解决方案1】:

    这应该使用以下语法。

    <bean id="props" class="java.util.Properties" >
        <constructor-arg>
            <props>
                <prop key="myKey">myValue</prop>
                <prop ...>
            </props>
        </constructor-arg>
    </bean>
    

    您正在利用 java.util.Properties 具有接受 Properties 对象的复制构造函数这一事实。

    我为一个 HashSet 做这个,它也有一个复制构造函数(就像 HashMaps 和 ArrayLists 一样),它工作得很好。

    【讨论】:

    • ApplicationContext app = new ClassPathXmlApplicationContext("app.xml"); System.out.println(app.getBean("props"));结果是 {}。知道如何解决这个问题吗?
    【解决方案2】:

    Spring 内置支持在应用程序上下文 XML 中指定属性。请参阅 Spring 参考文档的 section 3.3.2.4

    【讨论】:

    • 感谢您的回复。但我想避免创建一个 POJO 对象来存储属性。我阅读了您提供的链接,我可以指定属性,但总是在 定义元素内,以便将 bean 与 POJO 类链接。
    • 所以你希望实际的 是 java.util.Properties 的一个实例?
    • 这就是我要寻找的东西。谢谢你:)
    【解决方案3】:

    我认为使用 Spring 的 PropertyPlaceholderConfigurer 可以获得最佳结果,它允许您将常规 .properties 文件中的值与 bean 上定义的属性进行映射。

    http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer

    该示例展示了如何直接在 javax.sql.DataSource 实例上设置 JDBC 连接属性,从而无需中间“配置 bean”。

    【讨论】:

    • 感谢您的回答。您的解决方案似乎不错,但我不想创建单独的 .properties 文件,而是仅将属性值存储在 appContext.xml 文件中,并在 Java 代码中访问它们。
    • 那你要参考Mark提供的链接。它展示了如何在 XML 中声明 java.util.Properties 的实例: administrator@example.orgsupport@example.orgdevelopment@example.org
    • @HyLian 您不能将任意属性(看起来像 .properties 文件)放在 XML 文件中。您要么必须遵循 XML 结构(如上面提到的 @brd6644),要么将其放入单独的 .properties 文件中,正如他在帖子中提到的那样。
    【解决方案4】:

    最好的方法是使用spring PropertyPlaceholderConfigurer

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:yourconfigurationfile.properties</value>
            </list>
        </property>
    </bean>
    

    然后

    <bean id="configurationBean" class="mypackage.someClass">
        <property name="confValue1">
            <value>${myvalue1}</value>
        </property>
        ....
    </bean>  
    

    在你的configurationfile.properties中

    myvalue1= value1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 2015-04-13
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多