Spring - 从属性文件中检索值

sar*_*_pc 12 spring properties

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

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
       <list>
         <value>classpath:app.properties</value>
      </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

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

Ral*_*lph 24

使用Spring 3.0,您可以使用@Value注释.

@Component
class MyComponent {

  @Value("${valueKey}")
  private String valueFromPropertyFile;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*cin 9

实际上,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>`
Run Code Online (Sandbox Code Playgroud)

示例属性文件:

driver=com.mysql.jdbc.Driver
dbname=mysql:mydb
Run Code Online (Sandbox Code Playgroud)

或者你可以像创建bean一样

<bean name="myBean" value="${some.property.key}" /> 
Run Code Online (Sandbox Code Playgroud)

然后将此bean注入您的类