How to get the property value inside a spring bean class in my class ?

69,930

Solution 1

You can annotate your bean property like this, then spring will auto inject the property from your property file.

@Value("${url}")
private String url;

You dont have to extend PropertyPlaceholderConfigurer

Defining your bean like this will auto populate url as well, but annotation seems to be easiest way

<bean id="dataSource" class="org.tempuri.DataBeanClass">
   <property name="url" value="${url}"></property>
</bean>

Solution 2

Please do the following process to get property file value in class.

  1. Define the bean for property file in your spring.xml
    <util:properties id="dataProperties" location="classpath:/data.properties"/>

  2. keep your data.properties under src/main/resources.

  3. Use the following code to get value from property file for e.g to get value of url key in data.properties

private @Value("#{dataProperties['url']})
String url;

Share:
69,930
antony.ouseph.k
Author by

antony.ouseph.k

6920616d20616e746f6e792e2049206c6f76652070726f6772616d6d696e67

Updated on July 09, 2022

Comments

  • antony.ouseph.k
    antony.ouseph.k almost 2 years

    The things I did are:

    • Created a property file (data.properties).
    • Created a Spring.xml (I use property placeholder)
    • Created a bean class.
    • I have a class where I have to use the url value.
    • I have a web.xml which has context-param where i set the param value to the path of the Spring.xml file.
    • My codes are given below:

    Propertyfile:url=sampleurl

    Spring.xml:

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath*:data.properties*"/>
    
    </bean>
    
    <bean id="dataSource" class="org.tempuri.DataBeanClass">
        <property name="url" value="${url}"></property>
    </bean>
    

    beanclass

    public class DataBeanClass extends PropertyPlaceholderConfigurer{
    private String url;
    
    public String getUrl() {
        return url;
    }
    
    public void setUrl(String url) {
        this.url = url;
    }
    }
    

    entry in web.xml

     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:Spring*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    Now my problem is I dont know what method of PropertyPlaceholderConfigurer should I override and what should I do to set the value of variable url such that I can call it from other classes using getproperty() method.

  • antony.ouseph.k
    antony.ouseph.k over 10 years
    If I were to extend PropertyPlaceHolderConfigurer how should I do it ?
  • user1745356
    user1745356 over 9 years
    but what is the point if env.getProperty("url")) does not work?