In this tutorial, How to read and write properties file content in Spring framework and boot application.
In Spring applications, Properties files hold environment configurations such as database details and other configurations related to an application.
By default, the application.properties
file contains property configuration.
Spring boot loads application. properties by default from the below places
- classpath
- src->main->resources->
- current directory
Multiple environments like stage and prod have property files
In the Spring framework, There are multiple ways to read Java properties
How to read property values in Spring boot application?
let’s declare a properties file in the spring boot application
database=mysql
hostname=localhost
username=john
password=
Environment Object
org.springframework.core.env.The environment is a class to read properties files from the application. properties.
Inject Environment to Controller or service or component
Environment’s getProperty method returns the value for a given key in a property if the key does not exist, returns null
Here is a code for
reading application.properties with spring environment object
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class APIController {
@Autowired
private Environment environment;
@GetMapping("/api/helloworld")
public String sayHelloWorld(){
System.out.println("database:"+ environment.getProperty("database"));
System.out.println("hostname:"+ environment.getProperty("hostname"));
return "Hello World";
}
}
using @value annotation
@value
annotation is one of the simple approaches to read values directly from property files placed in the classpath in java.
Syntax: Here is an example of a property @value annotation with the below syntax.
@value("${property-key}")
The following are step by step for @value annotation
- Declare a component java class with @component annotation
- Declare private member variable with @value annotation syntax.
- This property holds the value of a given key using ${key} syntax.
- You can directly access the variable or with the java class
Let’s see an example
@Component
public class DatabaseConfig {
@Value("${hostname}")
private String hostname;
}
Parse properties file with @ConfigurationProperties in a Spring boot
@ConfigurationProperties in spring boot is another way to read properties files.
- Create a Java class with @component and @ConfigurationProperties annotation
- Create private member variables which are keys of a properties file
- Add setters and getters for a member variable. The object of this class holds the content of properties with values.
- As this class is declared a component, You can use it in the Spring application and use properties files.
Here is an example code
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties
public class DatabaseConfig {
private String database;
private String hostname;
private String username;
private String password;
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
How to write and update a key and values to a properties file in the Spring framework?
There are multiple ways we can write and update property files in the Spring Java app
using java File API
This is an example of using Java file API in the Spring application
- Create Java component in Spring boot
- Initialize a
File
object - Create a writer object using
FileWriter
- Create properties object and add new properties or update existing properties if the properties file exists
setProperties
method do update or add key and valuesstore
method of theproperties
object writes to the properties file, You have to add the comment which appends to the properties file as a comment
Here is a complete example read and writing a properties file
import java.io.*;
import java.util.Properties;
import org.springframework.stereotype.Component;
@Component
class PropertieWriter {
public void writeToProperties() {
FileReader reader = null;
FileWriter writer = null;
File file = new File("application.properties");
try {
reader = new FileReader(file);
writer = new FileWriter(file);
Properties p = new Properties();
p.load(reader);
p.setProperty("hostname","dev.com");
p.store(writer,"write a file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output of a file
#write a file
#Fri Aug 27 21:52:38 IST 2021
name=john
using DefaultPropertiesPersister class
org.springframework.util.DefaultPropertiesPersister
is an interface for the implementation of loading and saving the properties file.
Here is a line of code
DefaultPropertiesPersister method’s store() and load() which accepts properties object and streams. The store method uses outputStream java API and load() method uses InputStream API.
Here is a complete example to write to a properties file in Spring boot application
import org.springframework.stereotype.Component;
import org.springframework.util.DefaultPropertiesPersister;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
@Component
public class PropertiesConfig {
public void writeToApplicationProperties() {
try {
Properties properties = new Properties();
properties.setProperty("database", "oracle");
properties.setProperty("hostname", "localhost");
properties.setProperty("username", "root");
properties.setProperty("password", "root");
File file = new File("database.properties");
OutputStream outputStream = new FileOutputStream( file );
DefaultPropertiesPersister defaultPropertiesPersister = new DefaultPropertiesPersister();
defaultPropertiesPersister.store(properties, outputStream, "Comment");
} catch (Exception e ) {
System.out.println("An error during writing to database.properties");
e.printStackTrace();
}
}
}
Conclusion
You learned to read a properties file with keys and values in the Spring framework and also write and update properties files in Spring boot