Spring - Retrieve value from properties file

34,020

Solution 1

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

Solution 2

With Spring 3.0 you can use the @Value annotation.

@Component
class MyComponent {

  @Value("${valueKey}")
  private String valueFromPropertyFile;
}
Share:
34,020

Related videos on Youtube

saravana_pc
Author by

saravana_pc

Updated on April 08, 2020

Comments

  • saravana_pc
    saravana_pc about 4 years

    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?

  • saravana_pc
    saravana_pc about 13 years
    Thank you, I'm thinking of a solution where we could retrieve the values from ClassPathApplicationContext (without using annotations). Is it possible to assign an "id" to the PropertyPlaceHolderConfigurer bean and then retrieve the values from the bean?
  • Marcin
    Marcin about 13 years
    Yes you can add <bean name="propsBean" to your properties placeholder bean. Then you can retrieve this bean from context and load properties.
  • Betlista
    Betlista almost 11 years
    How can I get property value from PropertyPlaceholderConfigurer? I didn't find anything useful in documentation.

Related