Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Retrieve value from properties file

I have the following configuration in my 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?

like image 748
saravana_pc Avatar asked Apr 08 '11 09:04

saravana_pc


2 Answers

With Spring 3.0 you can use the @Value annotation.

@Component
class MyComponent {

  @Value("${valueKey}")
  private String valueFromPropertyFile;
}
like image 82
Ralph Avatar answered Oct 28 '22 19:10

Ralph


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

Example XML context definition:

<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 name="myBean" value="${some.property.key}" /> 

and then inject this bean into your class

like image 36
Marcin Avatar answered Oct 28 '22 19:10

Marcin