Spring Boot Environment Variables Example - onlyxcodes

Saturday 8 April 2023

Spring Boot Environment Variables Example

In Spring Boot, environment variables are variables that are used to configure and manage how an application behaves while operating in a certain environment.


These variables can be set independently of the application code, making it simple to modify the configuration without altering the application itself.


Environment variables in Spring Boot are commonly used to access environment variables. These variables offer a means to read values from many sources, including system properties, command-line arguments, and configuration files.


spring boot environment variables example

Let's look at a spring boot example of environment variables.


Choose the environment variable(s) you want to utilize and set them. Depending on your operating system and shell, there are numerous ways to accomplish this.


With Linux or macOS, for instance, you could use the export command to:


export DATABASE_URL=jdbc:mysql://localhost:3306/mydb

With the @Value annotation in your Spring Boot application, you can read the environment variable(s).


For example:


@Component
public class MyComponent {

    @Value("${DATABASE_URL}")
    private String databaseUrl;
    
    // ...
}

The @Value annotation may be one that you are already familiar with. It can be used to inject beans with property values.


The @Value annotation scans the environment for values that match those found in property files as well.


The DATABASE_URL environment variable's value is injected into the databaseUrl field of the MyComponent class in this example using the @Value annotation.


Use Environment Variables in the application.properties or application.yml Files

Environment variables can also be used to set up settings for your application.properties or application.yml files.


For example:


We must enclose this variable in braces or the syntax $.{..} in order to utilize it in Spring Boot's application.properties.


In this illustration, the DATABASE_URL environment variable's value is set as the spring.datasource.url property's value.


spring.datasource.url=${DATABASE_URL}

Spring Boot Environment Variables Naming Convention Example

In Spring Boot, there is a suggested naming convention for environment variables. The ideal approach is to split words in the variable name with underscores and all uppercase letters.


You may set the environment variable DATABASE_URL, for instance, if your application requires a database URL.


Here is an illustration of how you may use your Spring Boot application to read environment variables:


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

@Component
public class MyService {

    @Value("${DATABASE_URL}")
    private String databaseUrl;

    public void myMethod() {
        // Use the value of the environment variable
        System.out.println("Database URL: " + databaseUrl);
    }
}

The DATABASE_URL environment variable's value is injected into the databaseUrl field in the above example using the @Value annotation. To read the value of the environment variable, use the ${..} syntax.


Depending on your deployment scenario, there are different ways you can set environment variables. Setting environment variables in a shell script, a Dockerfile, or your cloud provider's configuration, for instance, are all examples.


Spring Boot Print Environment Variables On Startup Example

You can add a bean that implements the CommandLineRunner interface to the application context in a Spring Boot application to print environment variables when it first startup.


When the application startup, the run() method of the CommandLineRunner interface is used.


You can get the environment variables from the run() method and print them to the console using the System.getenv() method.


package com.onlyxcodes.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class EnvironmentPrint implements CommandLineRunner{

	@Autowired
	private Environment enviroment;
	
	@Override
	public void run(String... args) throws Exception {
		 System.out.println("Printing environment variables.....");
		 System.getenv().forEach((key, value) -> System.out.println(key + " : " + value));
		 System.out.println("Done printing environment variables.");
	}

}

In the above example, the CommandLineRunner interface is implemented by a component called EnvironmentPrint.


With the @Autowired annotation, we auto-wire the Environment object to utilize the System.


To read the environment variables and print them to the console, use the getenv() method.


When the program startup after you've built this bean, it will run and print the environment variables.


Since the same application code may be utilized across several settings with various configurations by simply altering the environment variables, using environment variables in Spring Boot enables a more flexible and dynamic application configuration.


Applications may now be deployed and managed more easily across several environments, including development, testing, and production.

2 comments:

  1. heyy, sorry I want to say something unrelated to this article. I am currently having difficulty creating a shopping chat and I saw your article at https://www.onlyxcodes.com/2020/10/add-to-cart-and-checkout-in-php.html. However, I am unable to access the source code even though I have subscribed. Could you please provide access to [email protected]? Thank you.

    ReplyDelete
  2. Hi, sorry I want to discuss something unrelated to this article. I am currently having difficulty creating a shopping chat and I saw your article at https://www.onlyxcodes.com/2020/10/add-to-cart-and-checkout-in-php.html. However, I am unable to access the source code even though I have subscribed. Could you please provide access to [email protected]? Thank you.

    ReplyDelete

Post Bottom Ad