Spring - 从属性文件中检索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5592897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:25:19  来源:igfitidea点击:

Spring - Retrieve value from properties file

springproperties

提问by saravana_pc

I have the following configuration in my applicationContext.xml:

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

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

Now, in my java class, how can I read the values from the file app.properties?

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

采纳答案by Marcin

Actually PropertyPlaceholderConfigurer is useful to inject values to spring context using properties.

实际上,PropertyPlaceholderConfigurer 可用于使用属性将值注入到 spring 上下文中。

Example XML context definition:

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>`

Example properties file:

示例属性文件:

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

Or you can create bean like

或者你可以像创建bean

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

and then inject this bean into your class

然后将此 bean 注入您的类

回答by Ralph

With Spring 3.0 you can use the @Value annotation.

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

@Component
class MyComponent {

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