Interview Questions

Spring - Load Properties from file

In this section, we will discuss about loading Properties file in Spring.

To load any property file in Spring, add the following bean definition in Spring configuration file.

XML Configuration

<bean id="propertyConfigurator" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <description>
        Configurer that replaces ${...} placeholders with values from a properties file
    </description>
   
    <property name="locations">
        <list>
            <value>classpath:user.properties</value>
        </list>
    </property>
</bean>

<bean id="user" class="in.techdive.spring.model.User">
    <description>
        Load Properties of the user bean from user.properties file
    </description>
   
    <property name="userName" value="${user.userName}" />
    <property name="passWord" value="${user.passWord}" />
    <property name="firstName" value="${user.firstName}" />
    <property name="lastName" value="${user.lastName}" />
    <property name="email" value="${user.email}" />
    <property name="country" value="${user.country}" />
    <property name="state" value="${user.state}" />
</bean>

The PropertyPlaceholderConfigurer spring api bean is used to replace the property name with corresponding property value in the spring configuration file.

The User bean for which the properties are to loaded is as follows.

User Bean Class

package in.techdive.spring.examples;

import java.io.Serializable;

public class User implements Serializable
{
    private static final long serialVersionUID = 0L;
    private long              userId;
    private String          userName;
    private String          passWord;
    private String          email;
    private String          firstName;
    private String          lastName;
    private String          country;
    private String          state;

    public User()
    {
    }

    //add getter/setter methods here
}

Now when Spring context loads, the User bean will be initialized with set of properties from user.properties file will be assigned to attributes(userId, userName, passWord... etc)

The contents of User.properties is as follows

User.properties

user.userName=Sunil
user.passWord=sunil123
user.firstName=Sunil
user.lastName=John
user.email=sjohn@gmail.com
user.country=US
user.state=California

Now lets test our code using LoadPropTester class.

LoadPropTester Class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.spring.examples;

public class LoadPropTester
{
    public static void main(String[] args)
    {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                new String[] { "classpath*:spring-LoadProperties.xml" });

        User usr = (User) ctx.getBean("user");

        System.out.println("Username = " + usr.getUserName());
        System.out.println("PassWord = " + usr.getPassWord());
        System.out.println("FirstName = " + usr.getFirstName());
        System.out.println("LastName = " + usr.getLastName());
        System.out.println("Country = " + usr.getCountry());
        System.out.println("State = " + usr.getState());
        System.out.println("Email = " + usr.getEmail());
    }
}

The above class initially loads the ApplicationContext from spring-LoadProperties.xml file available in class path. We can get the user bean from the context using getBean() method.

Output:

Username is Sunil
PassWord is sunil123
FirstName is Sunil
LastName is John
Country is US
State is California
Email is sjohn@gmail.com