How can you inject properties into a Spring application using environment variables?

Spring allows applications to read configuration values directly from environment variables, making it easy to externalize configuration and deploy the same application across different environments without code changes. Environment variables are commonly used for database credentials, API keys, server settings, and other environment-specific configurations.

Key Points

Example

Suppose an application requires a database URL that differs between development and production. Instead of hardcoding the value, an environment variable can be defined and injected at runtime.

Using @Value

@Component
public class DatabaseConfig {

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

    public void printUrl() {

        System.out.println(databaseUrl);
    }
}

Using Environment Interface

@Component
public class DatabaseConfig {

    @Autowired
    private Environment environment;

    public void printUrl() {

        String url =
            environment.getProperty("DB_URL");

        System.out.println(url);
    }
}

Using application.properties

app.name=${APP_NAME:MyApplication}

The value of APP_NAME is taken from the environment variable.

If the variable is not available, "MyApplication" is used as the default value.

Common Use Cases

Best Practice

Interview Tip

A concise interview answer is: Environment variables can be injected into Spring applications using @Value, the Environment interface, or @ConfigurationProperties. This externalizes configuration, improves security, and allows the same application to run across different environments without code modifications.

Last updated: 11 November 2026

Previous question: What are Spring profiles, and how do you start an application with a specific profile?

Next question: You have a conflict between beans in your application. How would you resolve it in Spring Boot?

More Spring Framework - Level II interview questions

All Spring Framework - Level II questions