SpringBoot
Environment Variables
Java
Configuration
Application Properties

Read environment variable in SpringBoot

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is a popular framework for building Java-based applications, providing a comprehensive set of tools to quickly set up robust applications with minimal configuration. One of the key features of Spring Boot is its ability to easily read environment variables. Environment variables are part of the operating system’s shell environment and provide a way to store configuration settings outside of the application, allowing for more flexible and scalable application deployments.

Why Use Environment Variables?

Environment variables serve several purposes in software development and deployment:

  • Configuration Management: They simplify the management of configuration settings for different environments (development, staging, production).
  • Security: Sensitive information, such as API keys or database credentials, can be stored as environment variables, keeping them separate from the codebase.
  • Portability: Applications can be easily moved between different environments without changing the code.

Reading Environment Variables in Spring Boot

Spring Boot provides multiple ways to read environment variables, making it convenient to configure applications dynamically.

Using @Value Annotation

The @Value annotation is a powerful tool in Spring Boot for injecting values into fields and methods. You can use it to read environment variables as follows:

java
1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.stereotype.Component;
3
4@Component
5public class MyService {
6
7    @Value("${MY_ENV_VAR:default_value}")
8    private String myEnvVar;
9
10    public void printEnvVar() {
11        System.out.println("Environment Variable: " + myEnvVar);
12    }
13}

In this example, MY_ENV_VAR is the name of the environment variable. If it's not set, default_value will be used as a fallback.

Using Environment Interface

The Environment interface allows you to access environment properties programmatically:

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.core.env.Environment;
3import org.springframework.stereotype.Component;
4
5@Component
6public class MyService {
7
8    @Autowired
9    private Environment env;
10
11    public void printEnvVar() {
12        String myEnvVar = env.getProperty("MY_ENV_VAR", "default_value");
13        System.out.println("Environment Variable: " + myEnvVar);
14    }
15}

Using @ConfigurationProperties

@ConfigurationProperties is another way to bind environment variables to a Java class:

java
1import org.springframework.boot.context.properties.ConfigurationProperties;
2import org.springframework.stereotype.Component;
3
4@Component
5@ConfigurationProperties(prefix = "myapp")
6public class MyAppProperties {
7
8    private String envVar;
9
10    public String getEnvVar() {
11        return envVar;
12    }
13
14    public void setEnvVar(String envVar) {
15        this.envVar = envVar;
16    }
17}

With this setup, you can access the environment variable using myapp.env-var.

Configuring Environment Variables

Environment variables can be set in various ways, depending on the operating system and development environment. Here are some examples:

Linux/MacOS

You can set an environment variable for a session using:

bash
export MY_ENV_VAR="This is a test"

Windows

To set an environment variable in a command prompt window:

cmd
set MY_ENV_VAR=This is a test

Docker

When running Spring Boot applications inside Docker containers, you can specify environment variables in the Dockerfile or with the docker run command:

dockerfile
# Dockerfile
ENV MY_ENV_VAR=This is a test
bash
docker run -e MY_ENV_VAR="This is a test" my-spring-boot-app

Table: Key Points for Reading Environment Variables in Spring Boot

MethodDescriptionExample Usage
@Value AnnotationInjects the environment variable directly into a field@Value("${MY_ENV_VAR:default_value}")
Environment InterfaceProgrammatically access environment variablesenv.getProperty("MY_ENV_VAR", "default_value")
@ConfigurationPropertiesBinds environment variables to a POJO-like structure@ConfigurationProperties(prefix = "myapp")
Terminal/Command-lineSet environment variables manually for different OSLinux: export VAR=value Windows: set VAR=value
DockerManage environment variables in containerized applicationsENV VAR=value in Dockerfile or -e VAR=value in docker run command

Best Practices

  1. Use Default Values: Always provide a default value when accessing environment variables to ensure application stability.
  2. Centralized Configuration: Use centralized configuration management tools like Spring Cloud Config to manage environment variables for large deployments.
  3. Secure Sensitive Data: Use environment variables for sensitive information to minimize exposure in the codebase.

By reading environment variables, your Spring Boot application can become more flexible and adaptive to different deployment environments, enhancing maintainability and scalability.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.