Monday, April 18, 2022

How to use Environment Variables in Spring Boot's application.properties file? Example Tutorial

How to use environment variable in Spring boot's application.properties is a major problem when your spring boot application running on different places like local, Jenkins, and OpenShift. So we need to make the data source file dynamic in the application.properties file. So let's have look at how to do this at how to use the env variable in Spring Boot's application.properties. So in this tutorial, We assume that you have knowledge of Spring boot and not going to talk about small details. 

There are many ways in Spring boot to manage configurations.

1. YAML or properties file
2. Command-line arguments.
3. Environmental variables.


So let's have a look at each way of configurations.


1. YAML or Property Files?

In most Spring boot applications, YAML or property files are used to manage configurations. YAML files are more structured and easy to read when compared with property files.
 
spring:
datasource:
password: password123
url: jdbc:h2:dev
username: admin04


As you can see, this is more readable than its property file alternative since it does not contain the repeated prefix.

As from the best practice, you need to put all the common configurations in the application.yml file like application name, queue name, topic name, port, context path, jackson date format and you can put all the configurations in applicaiton.yml file that are not going to change on the environmental variable.




2. Command Line Arguments

This is the best way to pass a small number of configurations in Spring boot is command-line arguments. This is used to activate the profiles. 

Below is a command-line argument.


$ java -jar spring-boot-student-example.jar --config.variable=value_passing


In the above line of code, the "config.variable" is the configuration variable and "value_passing" is the value that is passing to it. Command-line arguments take precedence over what defined in the config file. You can override the values defined in the config file using command-line arguments.


3. Environmental Variables

The major benefit of the configuration variable is that it allows us to execute the same build in multiple contexts simply by altering the value we provide to it. Spring also gives you the ability to manage the environmental-specific configurations.

So let's discuss more environment variables in this section with an example. Before moving to the example, please make sure to install Java 11 on your machine.

The project pom.xml file is given below. The spring-boot-starter allows you to include auto-configuration support, logging, and YAML.

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.codexlabs</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-database-server</name>
<description>Demo project for Spring Boot</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


So let's see how things are going with the application.properties file. This file contains the application configuration settings. Spring has some built-in application properties and we can also create our own configurations. 

Below is the application.properties file which we are using.


spring.main.banner-mode=off
spring.output.ansi.enabled=ALWAYS
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS})
                          {blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n
app.name=StudentExampleApp



As we discussed, this file contains the configuration settings. Spring has some built-in-application.properties and we can create our custom files also in here. The logging.pattern.console is referred to as logging with color support. In app.name, we configure the application name. 





So let's see the Applicaion.java file.


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class Application implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private Environment env;

    @Override
    public void run(String...args) throws Exception {

        logger.info("{}", env.getProperty("JAVA_HOME"));
        logger.info("{}", env.getProperty("app.name"));
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


The CommandLineRunner interface in the above application, indicates that a bean should run when it is contained within a SpringApplication. The @SpringBootApplication annotation indicates that the application is able to component scanning and also can auto-configure.


@Autowired
private Environment env;

So in here, we inject the environment variable with @Autowired which enables the getting properties.


logger.info("{}", env.getProperty("JAVA_HOME"));


So as mentioned in the above code segment, the env.getProperty("") will get the properties which is annotated with JAVA_HOME and can be used in our application.

logger.info("{}", env.getProperty("app.name"));


This is more like how we get the JAVA_HOME variable from the properties file, this will get app.name and can be used in our application. The environment can be used to get the properties from the application.properties.




After we run our Spring boot application with the following command,


$ mvn -q spring-boot:run


We can get the following kind of result.


21-10-12 Thu 07:02:21.218 INFO Application 
C:\Users\Program\AppData\Local\Programs\Java\openjdk-11\
21-10-12 Thu 07:02:21.210 INFO Application StudentExampleApp


That's all about how to use environment variable in Spring and Spring Boot application in Java. we have discussed how to use the environment variable in Spring Boot's application.properties configuration file. This is a must-know topic in Spring boot as everyone needs to deal with this kind of configuration in every application. So hope you understand what this tutorial is all about and happy coding. See you in the next tutorial.

Other Java and Spring Tutorial you may like
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • How Spring MVC works internally? (answer)
  • Spring Data JPA @Query Example (query example)
  • Spring Data JPA Repository (JpaReposistory example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Difference between @Component, @Service, and @Controller in Spring (answer)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)

Thanks for reading this article so far. If you find this Spring properties and environment variable tutorial and example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a Java beginner and want to learn the Spring Framework  from scratch, and looking for some best online resources then you can also check out these best Spring Framework courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring Framework from zero to expert.     

No comments :

Post a Comment