Inject properties files using spring annotations

In this article, we will learn how to inject properties files using spring annotations. We will also see a sample example which will help us to understand this topic more clearly.

Say in our application we use a database that is hosted on a 101.202.303.404 machine and we have hardcoded this value in our source code. Now because of some issues, we have to move the database to a different IP address 101.202.303.405. In this case, we have to update this IP address in our source codebase and build the application again.

Just like IP addresses, there can be multiple configuration values that can change from time to time. A few configs are database username, database password, logs file destination etc.

Now updating the codebase every time for these config changes is not a good idea and it is bad practice. So we can move all the config-related changes to a properties file.

Now, whenever we want to update some property value we will update the properties file instead of the source code. Hence we do not have to build the application again and again which saves a lot of time and the code looks clean.

Properties file

The properties file stores the information in the form of key-value pair.

key – property name
value – property value

Ex. db.username = Suraj

key – db.username
value – Suraj

We can store multiple key-value pairs in the same property file.

KeyValue
db.host101.202.303.404
db.port8090
db.usernameSuraj
db.passwordPassword

Sample Example

We will create an info.properties file in the src folder of the application.

info.properties

db.host = 101.202.303.404
db.port = 8090
db.username = Suraj
db.password = Password

We will create an application configuration file that will do the below

  • Enabling the component scanning so that the spring container will check the base package and register the beans with the container.
  • Load the properties file so that we can use the property values in our spring beans.
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.getinputs" />  
    
    <context:property-placeholder location="classpath:info.properties"/>  
    
</beans>

property-placeholder tag is used to externalize the properties in a different file.

Spring container will load the info.properties file from the classpath of the application. We will create a component class and use the info.properties configs in this class.

We have to make use of @Value annotation to fetch the value from the properties file. In other words, @Value annotation helps to inject values in the spring beans from the properties file.

If you want to know more about @Value annotation check this link https://www.baeldung.com/spring-value-annotation

DatabaseConfig.java

package com.getinputs;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DatabaseConfig {

  @Value("${db.host}")
  String host;

  @Value("${db.port}")
  String port;

  @Value("${db.username}")
  String userName;

  @Value("${db.password}")
  String password;

  public String getHost() {
    return host;
  }

  public String getPort() {
    return port;
  }

  public String getUserName() {
    return userName;
  }

  public String getPassword() {
    return password;
  }
}

The property-placeholder tag in the configuration file automatically configures the PropertyPlaceholderConfigurer bean which helps to replace the ${} placeholders with the actual values from the properties file.

Now we will create an application context and check if the properties file configs are injected in the Component class.

SpringDemoApp.java

package com.getinputs;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemoApp {
  public static void main(String[] args) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
    DatabaseConfig databaseConfig = context.getBean("databaseConfig", DatabaseConfig.class);
    
    System.out.println("DB host : " + databaseConfig.getHost());
    System.out.println("DB port : " + databaseConfig.getPort());
    System.out.println("DB username : " + databaseConfig.getUserName());
    System.out.println("DB password : " + databaseConfig.getPassword());

    context.close();
  }
}

Output:
DB host: 101.202 .303 .404
DB port: 8090
DB username: Suraj
DB password: Password

We can see from the output that spring is successfully able to fetch the values from the properties file and was able to inject that in the Component class.

https://github.com/getinputs/samples/tree/main/inject-properties-file

So this is all about how to inject properties files using spring annotations. I hope you found this article interesting and valuable. If you are having any concerns or questions about this article please comment below and please share it to help me grow.

Leave a Comment