Tuesday, August 29, 2023

How to access configuration values from application.properties file in Spring Boot? Example Tutorial

Hello guys, if you are wondering how to access a value defined in your spring application configuration file then you are not alone, many Java developer face the same challenge. How to access a value defined in the application.properties file in Spring Boot is a common question that arises when you dealing with large software applications. In software applications, you need to have different environments for the QA, production, and local. So as a solution for this, you can use different configurations and update the files separately without affecting other environments by using property files.


What is Property Files in Spring Boot?

Property files are used for multi-environment so that the properties can be dynamically configured per environment. By default, the spring applications have applications.properties which is located on src/main/resources directory. 

We need to add our configurations as this file is initially blank.

server.port = 5000
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.datasource.url=jdbc:mysql://localhost/itjobspro?createDatabaseIfNotExist=true
&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false
&serverTimezone=UTC
#change this username and password accordingly of the database...
spring.datasource.username=root
spring.datasource.password=
logging.level.root=INFO
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect


The sample file contains the username and password for the datasource, server port which the
application is running and logging level of the application.



How to create Property Files with YAML in Spring Boot?

Instead of .properties syntax, Spring support for the YAML files. So without using the application.properties files in your application, you can have application.yml files. 
spring:
 datasource:
 username: user
logging:
 level:
 root: INFO

So in here, took only the spring Datasource and logging level to demonstrate this and only the difference you can see here is the formatting of the content. Spring allows you to create multi-property files using @PropertySource annotation define in the configuration class.


How to access a value defined in the application.properties file in Spring Boot? Example Tutorial


3. Using @ConfigurationProperties annotation

The @ConfigurationProperties annotation is more expensive than @Value annotation. This will map values given the prefix of the group in properties. 
spring.project.username=root
spring.project.password=
spring.project.email=tutorial@email.com
So in here, all the properties have same prefix spring.project. So let's create the configuration class to map the values to of these properties using the @ConfigurationProperties.
 
Note : You need to annotate the class with @ConfigurationProperties and also with the @Configuration to inform that the class is a configuration class.

@ConfigurationProperties(prefix="spring.project")
@Configuration
public class DemoApp {
 private String username;
 private String password;
 private String email;
 //your methods in here.
}

So in here, the DemoApp instance can be used in anywhere within service layer to access property values with just autowiring to it.

@Autowired
private DemoApp demoApp;

public void print() {
 System.out.println("Your username: " + demoApp.getUsername());
 System.out.println("Your password: " + demoApp.getPassword());
 System.out.println("Your email: " + demoApp.getEmail());
}

4. Access values within Property Files

The @Value is a predefined annotation which is used to read values from any property files in the
class path. Only you need to provide the property values from property values with @Value
annotation
. Example is given below.

@Value("${spring.project.property}")

Then let's look at a real world example which is having datasource.username and add this value
to String field username.

@Value("${spring.project.username}")
String username;

So if we print the username, the output should be the value within spring.project.username value
in application.propery file. And if the spring.project.username value in the applicaiton.property file is not defined yet, the value will be null.

System.out.println(username);

You can also update the username which is annotated with @Value and this also able to temporarily
change the actual value of the property injected into variable during runtime.

username = "your_new_user_name"



5. Using Environment Object

This is the another way of accessing your values which is defined in Spring boot. This allows you to call the getProperty() method in classes and it accepts a single required parameter which is a String containing the property name and return the value of that property if that exits. 

So let's have an example which is accessing the spring.project.username property and store within a string value. 
@Autowired
private Environment env;

public void rootLevelLog() {
 return env.getProperty("logging.level.root");
}

This rootLevelLog() method will output the result as INFO log level and this will print the value within the logging.level.root as if it is exists.


That's all about how to access a value from application.properties in Spring Boot application. It's one of the essential concept every Java developer should know. The mostly used way of accessing the values in @Value annotation and autowiring with environment variable is rarely used. So see you in the next tutorial and until then bye ! So in this article, we covered the three different ways of accessing a value defined in the application.properties file in spring boot. 


Other Java and Spring Articles and Tutorials you may like to explore

Thanks for reading this article so far. If you like this tutorial about different ways to access values from application.properties in Spring Boot and Spring framework and then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.