saravana_pc
saravana_pc

Reputation: 2687

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?

Upvotes: 12

Views: 34548

Answers (2)

Ralph
Ralph

Reputation: 120881

With Spring 3.0 you can use the @Value annotation.

@Component
class MyComponent {

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

Upvotes: 25

Marcin
Marcin

Reputation: 1615

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

Upvotes: 9

Related Questions