【问题标题】:Spring - Retrieve value from properties fileSpring - 从属性文件中检索值
【发布时间】:2011-08-01 08:43:03
【问题描述】:

我的 applicationContext.xml 中有以下配置:

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

现在,在我的 java 类中,如何从文件 app.properties 中读取值?

【问题讨论】:

    标签: spring properties


    【解决方案1】:

    在 Spring 3.0 中,您可以使用 @Value 注释。

    @Component
    class MyComponent {
    
      @Value("${valueKey}")
      private String valueFromPropertyFile;
    }
    

    【讨论】:

    • 谢谢,我正在考虑一种解决方案,我们可以从 ClassPathApplicationContext 中检索值(不使用注释)。是否可以为 PropertyPlaceHolderConfigurer bean 分配一个“id”,然后从 bean 中检索值?
    【解决方案2】:

    实际上 PropertyPlaceholderConfigurer 对于使用属性将值注入到 spring 上下文中很有用。

    示例 XML 上下文定义:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName"><value>${driver}</value></property>
       <property name="url"><value>jdbc:${dbname}</value></property>
    </bean>`
    

    示例属性文件:

    driver=com.mysql.jdbc.Driver
    dbname=mysql:mydb
    

    或者你可以像创建bean一样

    <bean name="myBean" value="${some.property.key}" /> 
    

    然后将这个 bean 注入到你的类中

    【讨论】:

    • 是的,您可以添加&lt;bean name="propsBean" to your properties placeholder bean。然后您可以从上下文中检索此 bean 并加载属性。
    • 我如何从PropertyPlaceholderConfigurer 获得房产价值?我在文档中没有发现任何有用的东西。
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2012-05-12
    • 2018-10-06
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多